按q退出输出不正确的数学运算

时间:2017-06-21 19:50:27

标签: c

我正在尝试使用"按' q'退出"退出do ... while循环的功能,用于计算一系列用户定义的整数的平均值。在几个例子之后,我能够使退出值起作用,但它被包含在计算平均值的一部分中。

示例:

quixote@willow:~$ gcc sentinel-borked.c -o sentinel-borked
sentinel-borked.c: In function 'main':
sentinel-borked.c:22:13: warning: assignment makes integer from pointer without a cast [-Wint-conversion]
         sum = sum + value;
             ^
quixote@willow:~$ ./sentinel-borked 

Enter an answer string or q to quit: 1

Enter an answer string or q to quit: 1

Enter an answer string or q to quit: q

Count is: 3
Average is: 214197589.333333
quixote@willow:~$ 

我知道" q"被视为整数,但我不确定如何重写我的代码以逃避它。 :(

我能想到的最简单的解决方法是提示用户提供一个终点(即"你平均有多少个整数?")并使用它,但我真的想知道这个进行。

这是我到目前为止的代码。

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

int main ()
{
/* variable definition: */
int count, sum;
double avg;
char *value;

/* Initialize */
count = 0;
sum = 0;
avg = 0.0;

do {
// Loop through to input values
printf("\nEnter an answer string or q to quit: ");
fgets(value, 10, stdin);

    if (value >= 0){
        sum = sum + value;
        count = count + 1;
    }
    else {
            printf("\nValue must be positive");
}

} while (value[0] != 'q');

// Calculate avg. Need to type cast since two integers will yield an integer

printf("\nCount is: %d", count);
avg = (double) sum/count;
printf("\nAverage is: %lf\n", avg);


return 0;
}

编辑:用代码块内的纯文本替换了屏幕截图。原始图片仍位于:https://i.stack.imgur.com/qza1N.png

1 个答案:

答案 0 :(得分:1)

试试这个:

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

int main ()
{
/* variable definition: */
    int count, sum;

    double avg=0;

    char value[10]="";//make value an array or allocate memory for it using malloc and also null initiate it


/* Initialize */
    count = 0;

    sum = 0;

    avg = 0.0;

    fgets(value,10,stdin);

    if(value[strlen(value)-1]=='\n'){//if the user enters a string less than 10 chars a newline will also be stored inside the value array

        value[strlen(value)-1]='\0';//you need to remove that \n and replace it with null
    }

    else{

        while((getchar())!='\n');//just removing any extra chars left(when the user enters a string greater than 10 chars)
    }

    while(value[0]!='q'){//beware it will only check for the first char of the array to be q, anything else will still proceed the loop

        sum+=strtol(value,NULL,10);//use this to convert integers inside the array to long ints(many other ways exists)

        count++;

        fgets(value,10,stdin);//overwrite value each time to get input

        if(value[strlen(value)-1]=='\n'){

            value[strlen(value)-1]='\0';
        }

        else{

            while((getchar())!='\n');
        }

    }



// Calculate avg. Need to type cast since two integers will yield an integer

    printf("\nCount is: %d", count);

    if(count==0){
        printf("\nAverage is: %lf\n", avg);
    }
    else{
         avg = (double) sum/count;

         printf("\nAverage is: %lf\n", avg);
    }



    return 0;
}