Domanda

For a program I am attempting to write, I must create a program that asks the user to enter a number and calculate the total of all the numbers entered until the user enters a -1 to stop the loop. However, I cannot print the -1 or add it to the total but I am struggling with that.

#include <stdio.h>

int main ()
{
    int x, total;

    total = 0;
    x = 0;

    while (x <= -2 || x >= 0)
    {

        printf("Please enter a number: ");
        scanf("%d", &x);

        printf("You entered %d \n", x);

        totalSum = total + x;
        printf("total is %d \n", total);

    }

    printf("Have a nice day :) \n");
    printf("total is %d \n", total);

    return 0;
}

Any suggestions as to how I can stop the loop at -1 without it printing or adding to the total?

È stato utile?

Soluzione

You can check if the input is equals to -1 at the beginning of the loop, if so exit instead of calculating:

while(1) {
    printf("Please enter a number: ");
    scanf("%d", &x);      

    if (-1 == x)
      break;

     ...
 }

Altri suggerimenti

I'm sorry, but I just cringe when I see a while(1) loop driven solely by a conditional break. What about something like:

printf("Please enter a number: ");
while(scanf("%d", &x) == 1 && x != -1)
{
    // do work

    printf("Please enter a number: ");
}

One con to this method is the print is duplicated, but I believe that the pro of having the while conditional actually drive the loop more than makes up for it. An additional benefit is that scanf is also being checked here to make sure that it read in the next value correctly.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top