【发布时间】:2021-01-24 06:34:04
【问题描述】:
我需要编写一个程序,用户可以输入他们定义的任意多的数字,然后程序会尝试找出哪个是最小值和最大值。我面临的问题是:
- 当程序执行时,第二行将在
printf之前等待用户输入(数字) - “系统”错误似乎不可靠,有时有效,有时无效
- 程序只检查最后一个数字条目,因此它只显示最小和最大的最后一个数字
您可以在答案中给出提示或更正。非常感谢。
#include <stdio.h>
float max(float num1){
float a=0, b;
if(num1 > a){
a=num1;
}
return a;
}
float min(float num2){
float x=100, y;
if(num2 < x ){
x=num2;
}
return num2;
}
int main(){
int times, interval;
float mini, maxi, data_Input;
printf("How many number would you like to type in ? : ");
scanf("%d\n",×);
printf("Type in the number: ");
scanf("%f", &data_Input);
for(interval=2; interval<=times; interval++){
printf("\nType in the number: ");
scanf("%f",&data_Input);
while(data_Input<0){
printf("Invalid Input! Please re-enter the number:");
scanf("%f",&data_Input);
}
while(data_Input>100){
printf("Invalid Input! Please re-enter the number:");
scanf("%f",&data_Input);
}
}
maxi= max(data_Input);
mini= min(data_Input);
printf("The Lowest Number is %.2f\n", mini);
printf("The Highest Number is %.2f\n", maxi);
return 0;
}
输出:
How many number would you like to type in? : 5
70
Type in the number :
Type in the number : 90.7
Type in the number : 99
Type in the number : 30
Type in the number : 50
The Lowest Number is 50.00
The Highest Number is 50.00
【问题讨论】:
-
“错误“系统”似乎不可靠”这句话是什么意思?
-
欢迎来到 SO。您似乎使用
a和x作为当前最小值/最大值的存储,并且您似乎希望可以在函数调用之间使用它。您可能会再次阅读有关函数中变量的生命周期的信息。还有关于static关键字。 -
如果你想检查每一个输入,你应该用每一个输入调用你的函数。
min也应该返回 `x´。 -
另外,阅读 scanf 如何处理换行符。
-
对于用户交互,考虑抑制 scanf() 调用中的“\n”,否则它会挂起(参见stackoverflow.com/questions/40948635/…)。此外,因为 printf() 是一个缓冲函数。如果你在没有终止“\n”的情况下调用它,有时你可能会遇到没有显示的情况。为避免这种情况,请在每个 printf() 之后立即调用 fflush(stdout),而不使用 "\n"