lundi 12 août 2019

C++ "if" statement has resulted in an infinite output of numbers, how do I fix this? [on hold]

I'm attempting to write some simple code in C++ that will ask the user for a positive integer (n), then return all numbers between 1 and that integer (inclusive). It must return the values in order of 1 to n.

I have tried an "if" statement that prompts the user to enter a positive integer if the input is less than 0.

#include <iostream>

using namespace std;

int main()
{
    // Declare your variables
    int n, count;

    count = 0;
    // Get user input for a positive number
    cin >> n;
    // Check if number is positive
    if (n < 0) {
        cout << "You must enter a positive number!";
    }
    // Loop through to print numbers from 1 up to and including n
    while (count != n) {
        cout << (count + 1);
        count = count + 1;
    }
    return 0;
}

When this code is run and I enter a negative value to test it, it returns:

"You must enter a positive number! 
1234567891011121314151617181920212223242526272829303132333435363...(never ending list of numbers)"

Aucun commentaire:

Enregistrer un commentaire