Hello, I am new to C ++ and began studying from video tutorials (do not speak about this, for only the basic look at the lessons, then I will find the literature). I try to write a calculator that will give out after the operations whether the variables were negative or not. Here is the code:

#include <iostream> using namespace std; int main () { const int maxCnt = 10; float a[maxCnt], b[maxCnt]; char op[maxCnt]; //operator float res; //resultl int cnt = 0; char answer = 'y'; //answer while( (answer == 'y' || answer == 'Y') && cnt < maxCnt) { cout << "Enter expression: "; cin >> a[cnt] >> op[cnt] >> b[cnt]; switch (op[cnt]) { case '+': res = a[cnt]+b[cnt]; break; case '-': res = a[cnt]-b[cnt]; break; case '*': res = a[cnt]*b[cnt]; break; case '/': res = a[cnt]/b[cnt]; if (b == 0) { cout << "You can't use 0" << endl; system( "pause" ); return 0; } break; default: cout << "Bad operator" << endl; cout << "Continue? [y/n] "; cin >> answer; if(answer == 'y'|| answer == 'Y') continue; if(answer == 'n'|| answer == 'N') return 0; } cout << "Result: " << res << endl; cout << "Continue? [y/n] "; cin >> answer; cnt++; if(cnt == maxCnt) { system( "pause"); break; } } bool Negative = false; int Del = 0; int Umn = 0; for(int i=0; i<cnt; i++) { if(a[i]<0 || b[i]<0) Negative = true; if(a[i]>=0 && b[i]>=0) Negative = false; if(op[i]=='*') Umn++; else if(op[i]=='/') Del++; } if(Negative = false) cout << "Were not Negative"<<endl; else if(Negative=true) cout << "Were negative"<<endl; system ("pause"); return 0; } 

And when I enter positive values, it still outputs Were Negative. Tell me, what am I doing wrong? Maybe not to insert it?

  • 1) `` case '/': res = a [cnt] / b [cnt]; if (b == 0) {cout << "You can't use 0" << endl; system ("pause"); return 0; `` You divide by b[cnt] without checking for 0. The test b == 0 is meaningless in this case. 2) return in the case , it is better to avoid it. - fogbit
  • 1) How then to make it check for zero? 2) thanks, I already realized that it was stupid - Yegor Eremin
  • one
    If the numbers are integers, then just if (b[cnt] == 0) - fogbit

1 answer 1

Replace if(Negative = false)

on if(Negative == false)

similarly for true

In this case, you do not check for equality, but assign the Negative variable to false . This is a known C ++ syntax problem, so there is a recommendation to write if (false == Negative) . In this case, if you suddenly make a mistake and put an "=", the compiler will give a syntax error message.

  • thanks, really problems with it so far - Yegor Eremin
  • And what a compiler? Does he not give a warning about assignment within a conditional expression? - devoln
  • MSVC ++ 2010 Express. No, I did not give anything out - Yegor Eremin
  • @GLmonster, and which compilers issue such warnings? - avp
  • > which compilers issue such warnings? I have a Visual C ++ 2010 issue. Probably because I am doing the fourth level of warnings, and the rest of the default is the third. - devoln