【发布时间】:2016-09-28 21:46:06
【问题描述】:
好的,我是 C# 新手,我只想用控制台创建一个简单的计算器。我的问题是,当用户选择除零或除以零时,如何让用户为 num1 和 num2 选择不同的值,以防止程序由于未定义的结果而崩溃。我想我可以使用一个while循环来检查并查看答案是否为int,如果不是则重复整个程序。如何检查答案以验证结果是否为 int?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication1
{
class Program
{
public static void Main(string[] args)
{
int num1;
int num2;
string operand;
float answer;
while ()
{
Console.WriteLine("Please enter the first number.");
num1 = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Please enter which operator you would like to use(+,-,*,/)");
operand = Console.ReadLine();
Console.WriteLine("Please enter the second number.");
num2 = Convert.ToInt32(Console.ReadLine());
switch (operand)
{
case "+":
answer = num1 + num2;
Console.WriteLine(num1 + " + " + num2 + " = " + answer);
Console.ReadKey();
break;
case "-":
answer = num1 - num2;
Console.WriteLine(num1 + " - " + num2 + " = " + answer);
Console.ReadKey();
break;
case "*":
answer = num1 * num2;
Console.WriteLine(num1 + " * " + num2 + " = " + answer);
Console.ReadKey();
break;
case "/":
if (num2 == 0)
{
Console.WriteLine("You cannot devide by zero, please select a different number.");
num2 = Convert.ToInt32(Console.ReadLine());
}
else if (num1 == 0)
{
Console.WriteLine("You cannot devide zero, please select a different number.");
num1 = Convert.ToInt32(Console.ReadLine());
}
else
{
answer = num1 / num2;
Console.WriteLine(num1 + " / " + num2 + " = " + answer);
Console.ReadKey();
}
break;
}
}
}
}
}
【问题讨论】:
-
第一:始终使用相关语言进行标记。第二:示例应该最少,重点不在于您试图完成的目标,而是您在尝试完成它时遇到的具体问题,并且只包含足够的代码来重现该问题;见stackoverflow.com/help/mcve
标签: c# loops while-loop int calculator