gpt4 book ai didi

c - 按 q 退出输出不正确的数学

转载 作者:行者123 更新时间:2023-11-30 20:20:49 24 4
gpt4 key购买 nike

我正在尝试使用“按'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;
}

编辑:用代码块内的纯文本替换屏幕截图。原始图像仍位于:/image/qza1N.png

最佳答案

试试这个:

#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;
}

关于c - 按 q 退出输出不正确的数学,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44685108/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com