I would like to make a program which allows you to enter a number (say 145). It reads the 3 integers and prints the largest one.
int a, b, c, max;
cout << "Enter a, b and c: ";
cin >> a >> b >> c;
max = a;
if (b>max)
max = b;
if (c>max)
max = c;
cout << "Max is " << max << "\n";
I was think of using something like th开发者_如何学运维is, but I have no idea how to get the computer to read each individual integer. Also, I am new to programming so I'd like to keep it simple to understand.
Thanks!!
The way you're reading in the numbers (cin >> a >> b >> c
) requires them to be separated with whitespaces.
So if the intention is that each digit of 145
is interpreted as a number on its own, simply separate them with spaces when entering, like so: 1 4 5
.
If they have to be entered together, read them into char
variables and then convert to numbers (by subtracting '0'
).
If you meant digits instead of numbers, then you could use variables of type char
and then convert them to integers (although generally this would not be needed just to see which one is greater). Alternatively, you could read a single number (which seems to be what you want), and get each of the digits by succesively calling % 10, /= 10
.
Just use
char a, b, c, max;
instead of
int a, b, c, max;
and you will get what you want. Everything else leave unchanged
int main()
{
char a, b, c, max;
cout << "Enter a, b and c: ";
cin >> a >> b >> c;
max = a;
if (b>max)
max = b;
if (c>max)
max = c;
cout << "Max is " << max << "\n";
system("pause");
}
The easiest solution:
int number;
int max = 0;
cout << "Enter a number : ";
cin >> number;
while (number != 0)
{
if ((number % 10) > max) //Remainder of number / 10
{
max = number % 10;
}
number /= 10; //remove the last digit
}
cout << "The largest number was " << max;
精彩评论