i'm new at c++ i was trying to write a program and i found a problem with it even after i used a simpler program (bellow) i couldn't figure it out
when i input numbers such as 85 or 55, even though program shouldn't respond, it does
#include "stdafx.h"
#include <iostream>
#include <cmath>
using namespace std;
int main()
{
int a=0;
cin >> a;
if(a<25 || 30<a<50 || 60<a<75)
{
cout << "see it does't work\n";
}
return 0;
}
please help me
#include "stdafx.h"
#include <iostream>
#include <cmath>
using namespace std;
int main()
{
int a=0;
cin >> a;
if(a<25 || (30<a && a<50) || (60<a && a<75))
{
cout << "see it does't work\n";
}
return 0;
}
Your condition should be this :
if(a<25 || (30<a && a<50) || (60<a && a<75))
{
cout << "see it does't work\n";
}
Your if statement is malformed.
Each expression must evaluate to a true or false, and you cannot do things like upper/lower bounding.
Try this:
int main()
{
int a=0;
cin >> a;
if(a<25 || (a > 30 && a < 50) || (a> 60 && a <75))
{
cout << "see it does't work\n";
}
return 0;
}
Try
#include "stdafx.h"
#include <iostream>
#include <cmath>
using namespace std;
int main()
{
int a=0;
cin >> a;
if ((a<25) || ((30<a) && (a<50)) || ((60<a) && (a<75)))
{
cout << "see it does't work\n";
}
return 0;
}
Parenthesis are your friend. Each binary conditional expression will have a left part (a), operator (<) and right part (25). You have to break everything down to be expressed in this way.
what is happening in the below if statement is:
if(a<25 || 30<a<50 || 60<a<75)
when a = 85, 30 is always less than a, and hence true (which means 1 in c++ when converted to integer) and then 1 is always less than 50, hence true.
So, consider changing your if statement to
if ( a < 25 || (30 < a && a < 50) || ( 60 < a && a < 75) )
Theres no x < z < y
kind of statement in C++. You should separate those statements into binary parts: x < z && z < y
.
Let me rewrite that for you:
#include <iostream>
int main() {
int a = 0;
std::cin >> a;
if(a < 25 || (30 < a && a < 50) || (60 < a && a < 75)) {
std::cout << "See? It does work!\n";
}
return 0;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.