gpt4 book ai didi

c - 如何用 C 语言完成这个作业?

转载 作者:行者123 更新时间:2023-11-30 15:44:45 25 4
gpt4 key购买 nike

下面的程序提示输入来计算圆柱体的体积。当输入任意数量的非数字内容时如何终止该程序?

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

float areaCirc(float r) {
return (M_PI*r*r);
}

float volCyl(float r, float h) {
return (areaCirc(r)*h);
}

int main(void) {
float r, h;
int k = 0;
float volume;
float avgh = 0;
float toth = 0;

do {
scanf("%f%f",&r,&h);
if(r<=0 || h<=0) {
break;
}
volume = volCyl(r,h);
k = k++;
printf(" Cylinder %d radius %.2f height %.2f volume %.2f\n",k,r,h,volume);
toth = toth + h;
} while(r>0 && h>0);
avgh = toth/k;
printf("Total Height: %.2f\n",toth);
printf("Average Height: %.2f\n",avgh);

return EXIT_SUCCESS;
}

最佳答案

scanf() 返回分配的输入项的数量,该数量可能少于提供的数量,或者在早期匹配失败的情况下为零。如果在任何转换之前发生输入失败,该函数将返回 EOF (-1)。如果发生错误,scanf 将 errno 设置为非零值。因此,您可以检查 scanf 的输出,并确定是否应该退出,或者至少再尝试一次。我相信这就是 @Charlie 在他的评论中的意思,也是 @h3nr1x 答案如此有效的原因。

关于c - 如何用 C 语言完成这个作业?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19341607/

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