Re-type the code and fix any errors. The code should convert non-positive numbers to 1.if (userNum > 0) cout << "Positive." << endl;else cout << "Not positive, converting to 1." << endl; userNum = 1; cout << "Final: " << userNum << endl;
Question
Re-type the code and fix any errors. The code should convert non-positive numbers to 1.if (userNum > 0) cout << "Positive." << endl;else cout << "Not positive, converting to 1." << endl; userNum = 1; cout << "Final: " << userNum << endl;
Solution
Here is the corrected code:
if (userNum > 0) {
cout << "Positive." << endl;
} else {
cout << "Not positive, converting to 1." << endl;
userNum = 1;
}
cout << "Final: " << userNum << endl;
The problem with the original code was that the userNum = 1; statement was not included in the else block. This means that userNum would be set to 1 regardless of whether it was positive or not. By including this statement in the else block, it will only be executed if userNum is not positive.
Similar Questions
#include <iostream>using namespace std;int main() { int numItems; numItems = 6; if (numItems < 1) { cout << "c" << endl; } if (numItems > 9) { cout << "e" << endl; } if (numItems == 6) { cout << "h" << endl; } cout << "p" << endl; return 0;}
#include <iostream>using namespace std;int main() { int numSandwiches; numSandwiches = 5; if (numSandwiches < 1) { cout << "c" << endl; } else if (numSandwiches > 9) { cout << "e" << endl; } else { cout << "g" << endl; } cout << "r" << endl; return 0;}
What will be printed for the following code : if(x=0) cout<<”zero”; if(x>=0) cout<<”pos”; else cout<<”neg”;
This code produces an error message. Where will the error occur, and why?1 bool a = 1;2 int b = 2 + 4;3 float c = 4;4 cout<<a + b<<endl;
#include <iostream>using namespace std;int main() { int a = 10, b = 20, c = 100; if (a <= b || c <= b) { cout << "hello" << endl; } else if (a <= b || a <= c) { cout << "hi" << endl; } else { cout << "hey" << endl; }}Options: Pick one correct answer from belowhellohiheyhello hi
Upgrade your grade with Knowee
Get personalized homework help. Review tough concepts in more detail, or go deeper into your topic by exploring other relevant questions.