0

if i text 21 it stacks. program says you are a child. you are a teenager. you are adult. how can i delete this "stack". #include <iostream> using namespace std; int main() { int age; cin>>age; if (age>=14){ cout<<"You're a Teenager"<<endl; } if (age>=18){ cout<<"You're adult"<<endl; } if (age>=0){ cout<<"You're a Child"<<endl; } else{ cout<<"Are u stupid ?"<<endl; } return 0; }

18th Jul 2016, 10:34 AM
Peter Müller
Peter Müller - avatar
4 Respuestas
+ 1
Hi Peter, If you input age as 21, let's go through it step by step. Is 21 greater than or equal to 14? Yes. cout << Is 21 greater than or equal to 18? Yes. cout << Is 21 greater than or equal to 0? Yes. cout << This is your problem. The best way I could recommend a fix for this is to nestle the if-else statements, like this: if (age >= 18) { cout << } else { if (age >= 14) { cout << } else { if (age >= 0) { cout << } else { cout << } } } Thanks for your question!
18th Jul 2016, 11:50 AM
Cohen Creber
Cohen Creber - avatar
+ 1
Thank you! it worked as you said. But i found another answer: I could always after an if- Loop write break; ;)
18th Jul 2016, 1:22 PM
Peter Müller
Peter Müller - avatar
0
You don't need to nest them like that. You can just do: if (condition) { } else if (condition) { } else { }
18th Jul 2016, 5:47 PM
Christian Roos
Christian Roos - avatar
0
If you solve problem via break; you should write expressions in the correct order.
30th Dec 2016, 2:41 PM
pukenot