Reputation: 59
So I have almost completed my program but I keep getting this error for the subtraction operator. I have searched throughout my book and the internet but can find no fix for this. Is anybody able to tell me what is wrong with this code?
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();
}
}
}
Upvotes: 2
Views: 2512
Reputation: 1790
Console.Write("Answer is: " + int1 - int2);
You are first concatenating a string with int1, resulting in a string. Then you try to substract this string with int2.
Try this :
Console.Write("Answer is: " + (int1 - int2));
Thus you will first evaluate (int1 - int2)
and then concatenate it.
By the way, you will also have to do it for the '+' operator. Else you will concatenate int2 to int1. For the other operators, it should work thanks to the precedence on '+'.
Upvotes: 6
Reputation: 2171
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));
Upvotes: 1
Reputation: 33149
Use a comma to separate parameters in Console.Write and use a placeholder {0}, like so:
Console.Write("Answer is: {0}", int1 - int2);
This does not confuse the compiler.
Upvotes: 1