Reputation: 3
My Comp Sci teacher gave us 2 basic C++ tasks to do for homework. I've managed to do the first one, but this second one is confusing me. I'm supposed to write code that recognizes if one value is larger than the other, and print out a message saying if one value is larger or not larger than the other. The code:
#include<iostream>
using namespace std;
int main() {
int num1, num2;
cout << "Unesi broj" << endl;
cin >> num1, num2;
if (num1 > num2) {
cout << "First number is bigger than the second" << endl; }
else if (num1 < num2); {
cout << "First number isn't bigger than the second" << endl;
}
return 0;
}
If anyone could help me out it'd be amazing, since this is a graded task.
Upvotes: 0
Views: 1412
Reputation: 908
Problems:
std::cin >> num1, num2;
only affects the first argument. The comma operator doesn't make std::cin
apply num2
(More info about how comma operator works here).else if (num1 < num2);
does not guard the block cout << "First number isn't bigger than the second" << endl;
because of the semicolon after the condition so cout << "First number isn't bigger than the second" << endl;
will always execute.else if
guarded the block your solution is wrong when num1 == num2
: It does not print anything.Solutions:
,
) with >>
.else if (num1 < num2)
.else if (num1 < num2)
with else if (num1 <= num2)
or, even better, with else
.Additional information:
using namespace std;
is considered a bad practice (More info here).Full code:
#include <iostream>
int main() {
int num1, num2;
std::cout << "Enter numbers:" << std::endl;
std::cin >> num1 >> num2;
if (num1 > num2)
std::cout << "First number is bigger than the second." << std::endl;
else
std::cout << "First number isn't bigger than the second" << std::endl;
return 0;
}
Upvotes: 1