所以我差不多完成了我的程序但是我一直在为减法运算符得到这个错误。我在我的书和互联网上搜索过但是找不到解决方法。有人能告诉我这段代码有什么问题吗?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication14
{
class Program
{
static void Main(string[] args)
{
int int1;
int int2;
char oper;
Console.Write("Enter first integer: ");
int1 = Convert.ToInt32(Console.ReadLine());
Console.Write("Enter operator (+,-,*, / or %)");
oper = Convert.ToChar(Console.ReadLine());
Console.Write("Enter first integer: ");
int2 = Convert.ToInt32(Console.ReadLine());
if(oper == '+')
Console.Write("Answer is: " + int1 + int2);
if (oper == '-')
Console.Write("Answer is: " + int1 - int2);
if(oper == '*')
Console.Write("Answer is: " + int1 * int2);
if(oper == '/')
Console.Write("Answer is: " + int1 / int2);
if(oper == '%')
Console.Write("Answer is: " + int1 % int2);
Console.ReadKey();
}
}
}
答案 0 :(得分:6)
Console.Write("Answer is: " + int1 - int2);
您首先将字符串与int1连接,从而产生一个字符串。 然后你尝试用int2减去这个字符串。
试试这个:
Console.Write("Answer is: " + (int1 - int2));
因此,您将首先评估(int1 - int2)
,然后将其连接起来。
顺便说一句,您还必须为'+'运算符执行此操作。否则,您将int2连接到int1。 对于其他运算符,它应该工作,这要归功于'+'的优先级。
答案 1 :(得分:3)
Console.Write("Answer is: {0} ",int1 - int2);
答案 2 :(得分:1)
使用逗号分隔Console.Write中的参数并使用占位符{0},如下所示:
Console.Write("Answer is: {0}", int1 - int2);
这不会混淆编译器。
答案 3 :(得分:1)
if(oper == '+')
Console.Write("Answer is: " + (int1 + int2));
if (oper == '-')
Console.Write("Answer is: " + (int1 - int2));
if(oper == '*')
Console.Write("Answer is: " + (int1 * int2);
if(oper == '/')
Console.Write("Answer is: " + (int1 / int2));
if(oper == '%')
Console.Write("Answer is: " + (int1 % int2));