Jeff - 7 months ago 40

C++ Question

I am new to C++ so bear with me please. I know this is a very beginner problem.

I am supposed to have the user input a number. Ex: 4. This is how many numbers we will read through and find the largest. My program allows the user to input a number and then list 4 integers. When I print out the largest number, it is not the largest one. If anyone could explain what I am doing wrong, that would be much appreciated!

`#include <iostream>`

using namespace std;

int main ()

{

float largest;

float max_input;

float total = 0;

float input;

myDefault:

cout << "Enter a positive number to start: ";

cin >> max_input;

if (max_input >= 0)

{

total++;

do {

cout << "Enter integer: ";

cin >> largest;

if (largest >= 0)

{

total++;

if (input > largest)

{

input = largest;

}

}

}while (total <= max_input);

cout << "\nThe largest number you entered is: " << largest << ".\n\n";

}

else

{

cout << "Error. Enter a Positive number to start. \n";

goto myDefault;

}

return (0);

}

Answer

Try something like:

```
#include <iostream>
using namespace std;
int main ()
{
float largest = 0;
float max_input;
float total = 0;
float input;
myDefault:
cout << "Enter a positive number to start: ";
cin >> max_input;
if (max_input >= 0)
{
total++;
do {
cout << "Enter integer: ";
cin >> input;
if (input >= 0)
{
total++;
if (input > largest)
{
largest = input;
}
}
} while (total <= max_input);
cout << "\nThe largest number you entered is: " << largest << ".\n\n";
}
else
{
cout << "Error. Enter a Positive number to start. \n";
goto myDefault;
}
return (0);
}
```

Here you are storing `input`

in `largest`

, checking if the next user input is larger than the largest.