【问题标题】:Sum of numbers and cubing numbers in C#C#中的数字总和和立方数字
【发布时间】:2014-07-22 08:46:00
【问题描述】:

嘿,我对 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++;

     }
  }
}

【问题讨论】:

  • 请包含控制台输出

标签: c# sum


【解决方案1】:

如果要显示最后的总和,而不是每个求和过程,请更改打印语句的位置

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);
}

else if 块也是如此。

【讨论】:

  • 谢谢它的作品没有意识到它是如此简单!当我做偶数时,我只会得到一个重复的总和:)
  • @user3863768 很高兴我能提供帮助
【解决方案2】:

您可以尝试使用 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);

【讨论】:

    猜你喜欢
    • 2010-10-03
    • 1970-01-01
    • 2019-03-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-03
    • 2021-02-21
    • 1970-01-01
    相关资源
    最近更新 更多