#include <iostream>
usingnamespace std;
void main()
{
long x, y, z;
cout << "Please enter two whole numbers:" << endl;
cin >> x >> y;
if (x > y) {
cout << x << " is the largest number" << endl;
}
else{
cout << y << " is the largest number" << endl;
}
cout << "Please enter another whole number" << endl;
cin >> z;
switch (z){
case 1:
cout << 'ONE' << endl;
break;
case 2:
cout << 'TWO' << endl;
break;
default :
cout << "Out of range" << endl;
}
}
The first part of the program runs fine, but switch statement is giving me a lot of trouble. I'd like for it print out 'ONE' if I enter 1 and 'TWO' if I enter 2, but I get 5197381 for 1 and 5527375 for 2. I've tried changing it to:
Doesn't your compiler say anything about your code? For example:
25:11: warning: multi-character character constant [-Wmultichar]
29:11: warning: multi-character character constant [-Wmultichar]
5:11: error: '::main' must return 'int'
What is the difference between line 9 and line 25 in your code?
#include <iostream>
usingnamespace std;
int main() // <--
{
int x = 0, y = 0, z = 0;// <-- should initialise, use int for whole numbers
cout << "Please enter two whole numbers:" << endl;
cin >> x >> y;
if (x > y) {
cout << x << " is the largest number" << endl;
}
else{
cout << y << " is the largest number" << endl;
}
cout << "Please enter another whole number" << endl;
cin >> z;
switch (z){
case 1:
cout << "ONE" << endl; // <--" "
break;
case 2:
cout << "TWO" << endl; // <-- " "
break;
default :
cout << "Out of range" << endl;
}
}
@keskiverto Wow, I feel so stupid. Can't believe I used single quotes.
@kemort It worked after I switched the single quotes on line 25 and 33.
The void main() didn't seem to affect the results. I'm using Visual Studio and my professor uses void main() at the start of all his programs, but most people seem to use int main(). Is it just based on the compiler you're using or is int main() the preferred/standard way to start basic C++ programs?
Also, does initializing the variables with long instead of int affect the speed of the program or could it impact the results as well?
long is OK for bigger integers. I actually misread it as float when I focussed on your 'whole number' comment. That's life. I guess long takes a little longer processing time but it would take a lot of longs for that difference to be significant/noticeable.
void main() is out of date with the standard. Your compiler is probably a bit old. Handy if you ever work on maintaining old code.
Irrespective of the data type eg long or int, it is good programming practice to always initialize variables.