Reputation: 61
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 this, 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!!
Upvotes: 1
Views: 3444
Reputation: 91
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;
Upvotes: 0
Reputation: 541
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");
}
Upvotes: 0
Reputation: 81349
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
.
Upvotes: 0
Reputation: 500317
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'
).
Upvotes: 2