创建一个确定数字是奇数/偶数的应用程序

时间:2013-10-07 21:53:05

标签: c# operator-keyword

我对C#很新,我遇到了一些问题。我已经尝试了一段时间,我似乎无法做到正确。我想我有这个想法,但我只是不知道如何让它发挥作用。在我的书的章节中也没有任何例子。我需要“创建一个读取整数的应用程序,然后确定并显示它是奇数还是偶数。让用户输入一个整数并输出到控制台:您输入的数字是:输入值+偶数或奇数”I'我希望我能在这里得到一些帮助。也没有找人做这项工作。如果你能解释一下,请做!

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;

    namespace Student_Challenge_Lab_2
    {
       class Program
   {
      // main method begins the execution of C# program
      static void Main(string[] args)
      {
         int number1; // declares the integer to be added

         // following code prompts user to input the two sets of integers
         Console.Write("Please enter your integer: ");
         number1 = Convert.ToInt32(Console.ReadLine());

         int %(number1, ); 
         // the program now tests to see if the integer is even or odd. If the remainder is        0 it is an even integer
         if (% == 0)
            Console.Write("Your integer is even.", number1);
         else Console.Write("Your integer is odd.", number1);


          }
       } // end main
    } // end Student challenge lab 2

3 个答案:

答案 0 :(得分:4)

每个二元运算符都应该以一种形式使用:

[argument1] [THE OPERATOR] [argument2]

%也是二元运算符,其使用方式与+/相同。所以类似地,如果/运算符产生除法运算的结果:

float result = (float)number1 / number2;

%将以相同的方式生成余数:

int remainder = number1 % number2;

剩下的就是当计算0的模数时,甚至会生成2个余数的数字。

答案 1 :(得分:1)

我不确定你是如何提出你在这里使用的语法

int %(number1, ); 

您已将number1定义为上面的int。您想要定义一个新变量,该变量包含number1上mod操作的值。如下所示:

int remainder = number1 % 2;

然后

if (remainder == 0)

答案 2 :(得分:-1)

在这里,我完成了你的作业......

The ?? operator is called the null-coalescing operator and is used to define a default value for nullable value types or reference types. It returns the left-hand operand if the operand is not null; otherwise it returns the right operand.

The % operator computes the remainder after dividing its first operand by its second. All numeric types have predefined remainder operators.

我还添加了一个Console.ReadKey,以便您可以看到输出,按任意键即可结束该应用。

    using System;

namespace Student_Challenge_Lab_2
{
    internal class Program
    {
        // main method begins the execution of C# program
        private static void Main(string[] args)
        {
            // following code prompts user to input the two sets of integers
            Console.Write("Please enter your integer: ");
            var number1 = Convert.ToInt32(Console.ReadLine());
            // the program now tests to see if the integer is even or odd. If the remainder is        0 it is an even integer
            Console.Write(number1 % 2 == 0 ? "Your integer ({0}) is even." : "Your integer ({0}) is odd.", number1);
            Console.ReadKey();
        }
    }
    // end main
}
// end Student challenge lab 2