2014-07-22 2 views
0

안녕하세요 저는 C#에 약간 새로운 것이므로 오늘 1 주일이 지났습니다. 필자는 이것을 멀리까지 얻을 수 있었지만, 나는 그냥 짝수의 합을 넣은 것처럼 보였다. 나는 전체 출력을 얻었고, 마지막 숫자는 마지막으로 보여주고 싶을 뿐이라는 것을 제외하고는 합계되었다. 어떤 도움이라도 몹시 고맙고 끔찍한 코드에 사과드립니다. 감사합니다C#의 숫자와 큐브 숫자의 합

using System; 

public class Test 
{ 
    public static void Main() 
    { 

     int j = 0; //Declaring + Assigning the interger j with 0 
     int Evennums = 0; // Declaring + Assigning the interger Evennums with 0 
     int Oddnums = 0; //Declaring + Assigning the interger Oddnums with 0 
     System.Console.WriteLine("Calculate the sum of all even numbers between 0 and the   user’s number then cube it!"); //Telling console to write what is in "" 
     Console.WriteLine("Please enter a number"); 
     uint i = uint.Parse(Console.ReadLine()); 
     Console.WriteLine("You entered: " + i); 
     Console.WriteLine("Your number cubed: " + i*i*i); 

     if (i % 2 == 0) 
     while (j <= i * i * i) 
      { 
      if(j % 2 == 0) 
      { 
       Evennums += j; //or sum = sum + j; 
       Console.WriteLine("Even numbers summed together " + Evennums); 
      } 
      //increment j 
      j++; 


      } 
    else if(i%2 != 0) 
     //reset j to 0 like this: j=0; 
     j=0; 
     while (j<= i * i * i) 
     { 
      if (j%2 == 0) 
      { 
       Oddnums += j; 
       //Console.WriteLine(Oddnums); 
      } 
      //increment j 
      j++; 

    } 
    } 
} 
+0

콘솔 출력에게 그것은 단순한 것을 몰랐어요 작동 – Robin

답변

0

마지막 합계를 표시 할 경우,하지만 모든 합산 과정은 블록 경우

if (i % 2 == 0) 
{ 
    while (j <= i * i * i) 
     { 
     if(j % 2 == 0) 
     { 
      Evennums += j; //or sum = sum + j; 

     } 
     //increment j 
     j++; 


     } 
     Console.WriteLine("Even numbers summed together " + Evennums); 
} 

같은 일이 다른 적용 인쇄 문의 위치를 ​​변경합니다.

+0

감사를 기입하십시오! 나는 단지 짝수를 할 때 중복 된 합계를 얻는다. – user3863768

+0

@ user3863768 기꺼이 도와 줄 수있다. – epipav

0

당신은 LINQ를 사용하면 아래와 같이 원하는 것을 달성하기 위해 시도 할 수 :

// Calculate the cube of i. 
int cube = i*i*i; 

int sum = 0; 
string message; 

// Check if cube is even. 
if(cube%2==0) 
{ 
    sum = Enumerable.Range(0,cube).Where(x => x%2==0).Sum(); 
    message = "The sum of the even numbers in range [0,"+cube+"] is: "; 
} 
else // The cube is odd. 
{ 
    sum = Enumerable.Range(0,cube).Where(x => x%2==1).Sum(); 
    message = "The sum of the odd numbers in range [0,"+cube+"] is: "; 
} 

// Print the sum. 
Console.WriteLine(message+sum);