2016-10-02 3 views
0

Итак, я пишу базовую программу, которая запрашивает у пользователя ввод числа, и цикл будет продолжаться до тех пор, пока они не введут определенное число. (25). После этого программа добавит все введенные цифры. Проблема в том, что когда я набираю номер выхода, цикл не выходит, и я не уверен, почему.Незначительная проблема с Do While Loop

double userNum = 0; 
double sum = 0; 

do { 
    printf("Please enter a number you would like to add [Enter 25 to exit at any time]:\n"); 
    scanf("%f", &userNum); 
    sum = sum + userNum; 
} while (userNum != 25); 

printf("The sum of all the numbers you entered:%f\n", sum); 

Также Im не уверен, что сумма рассчитана правильно, так как Ive никогда не смог выйти из цикла.

+0

Хороший компилятор с предупреждениями поддержкой будет сообщили о проблеме, связанной с 'зсапЕ ("% F ", & userNum);' Сэкономьте время! Получите лучший компилятор или убедитесь, что все предупреждения включены. – chux

ответ

0

Вы используете неправильный тип данных, идут с целыми числами вместо:

int userNum = 0; 
int sum = 0; 
do { 
    printf("Please enter a number you would like to add [Enter 25 to exit at any time]:\n"); 
    scanf("%d", &userNum); 
    sum = sum + userNum; 
} while (userNum != 25); 
printf("The sum of all the numbers you entered:%d\n", sum); 
1

Рассмотрите возможность использования fgets для ввода и разобрать значение с sscanf. С помощью этого вы можете ввести завершение или выход для завершения цикла вместо 25. Формат сканирования двойного значения - %lf.

#include <stdio.h> 
#include <string.h> 
#include <stdlib.h> 

int main(void) 
{ 
    char input[99] = ""; 
    double userNum = 0; 
    double sum = 0; 
    while (1) { 
     printf("Please enter a number you would like to add [Enter 25 to exit at any time]:\n"); 
     if ((fgets (input, sizeof (input) , stdin))) { 
      if (strcmp (input, "25\n") == 0) {//could use exit, done ... instead of 25 
       break; 
      } 
      if ((sscanf(input, "%lf", &userNum)) == 1) {//sscanf successful 
       sum = sum + userNum; 
      } 
     } 
     else { 
      break;//fgets failed 
     } 
    } 
    printf("The sum of all the numbers you entered:%f\n", sum); 

    return 0; 
} 
0

Вы хотите использовать контрольную петлю с часовым (25 - ваш дозорный). Вот что я хотел бы написать:

#include <stdio.h> 


    int main() 
    { 
     double userNum = 0; 
     double sum = 0; 

     while (userNum != 25) { //sentinel controlled loop 

     puts("Please enter a number you would like to add [Enter 25 to exit    at any time]:"); // puts automatically inputs a newline character 
     scanf("%lf", &userNum); // read user input as a double and assign it to userNum 
     sum = sum + userNum; // keep running tally of the sum of the numbers 

     if (userNum == 25) { // Subtract the "25" that the user entered to exit the program 
     sum = sum - 25; 
     } // exit the if 
     } // exit while loop 

     printf("The sum of all the numbers you entered:%lf\n", sum); 

    } // exit main 

ИЛИ, вы можете придерживаться делать ... в то время:

// Using the do...while repetition statement 
    #include <stdio.h> 

    // function main begins program execution 
    int main(void) 
    { 
     double userNum = 0; // initialize user input 
     double sum = 0; //initialize sum as a DOUBLE 

     do {            
     puts("Please enter a number you would like to add [Enter 25 to exit at any time]:"); // puts automatically inputs a newline character 
     scanf("%lf", &userNum); // read user input as a double and assign it to userNum 
     sum = sum + userNum; // keep running tally of the sum of the numbers 


     if (userNum == 25) { // Subtract the "25" that the user entered to exit the program 
     sum = sum - 25; 
     } // end if statement 
     } while (userNum != 25); // end do...while 

     printf("The sum of all the numbers you entered:%lf\n", sum); 

    } // end function main