2008\projects\lap7.ex3\lap7.ex3\ex3.cpp(34) : warning C4700: uninitialized local variable 'd' used
2008\projects\lap7.ex3\lap7.ex3\ex3.cpp(39) : warning C4700: uninitialized local variable 'q' used
the warning appears here!
else if (x==d)
{
divide = x1/x2;
cout << divide << endl;
}
else if (x==q)
cout << "Quit" << endl;
return 0;
The problem is relatively straightforward. What is wrong with your program is you have not put any value into the variables d or q. That means they are uninitialized, and you cannot compare x to something that doesn't have any value in it. The statements if(x==d) and if(x==q) therefore are in fault.
you cannot compare x to something that doesn't have any value in it
If only that were the case. But the thing is, there IS a value at that point. However, it might be any kind of random trash value that occupied the memory the variable refers to before.
"But there is no value for d and q !" I think that can not be the case. Variables must have values before using them.
I think you post your complete main function, people can figure out it more clearly.
here is the problem:
Write a C++ calculator that takes two numbers and a letter indicating an
operation to be performed. The user enters the letter and the program performs the
operation depending on the letter as follows:
A: Add (the two numbers)
S: Subtract
M: Multiply
D: Divide
Q: Quit (exit the program).
and here is my answer:
#include<iostream>
using namespace std;
int main()
{
int x1,x2;
char x;
char a,s,m,d,q;
int add,subt,multip,divide;
cout << "Enter the tow numbers: " << endl;
cin >> x1 >> x2;
I don't have experience with C++ (I used fortran mostly), it is better to use the "switch case" control, but since you used "if", you can stick with that. But the "else" statement is completely unnecessary, if not wrong, I would remove them. (If the "IF" doesn't meet, it just skips {} to go to the next statement.)
Secondly, you have to initiate value for a,s,m,d,q. I think you have problem with distinguishing the names of variables with their values, do a = "a", s ="s"... to see how it goes. If it works then I am right, and you can give some minutes to think about that.
And if I were you I would put all the semicolon at the end of a statement, including };. That builds up the concept of statements and block of statements more clearly.
Sorry, it was my fault using "a", it should be 'a' in C++.
Use:
char a = 'a', s = 's', m = 'm', d = 'd', q = 'q';
I checked your code, with "else"s removed, it ran (but didn't check if it is correct.)