提问人:bartukilickaya 提问时间:3/20/2020 最后编辑:Vlad from Moscowbartukilickaya 更新时间:3/20/2020 访问量:426
从用户那里读取数字,直到给出负数,返回最高、最低、范围和数字计数?
Reading numbers from the user until negative number is given, returning highest,lowest,range and number count?
问:
#include <stdio.h>
#include <math.h>
int main(void) {
int a,count,highest,lowest,range;
for(count=0;scanf("%d",&a) >= 0;count++){
if(count == 0){
highest = a;
lowest = a;
}
if(a > highest){
highest = a;
}
if(a < lowest){
lowest = a ;
}
}
range = highest - lowest;
printf("%d\n %d\n %d\n %d\n",count,highest,lowest,range);
return 0;
}
问题是这个程序在我按 CTRL D 之前不会停止,但是我希望它在我输入负数时停止,如您看到的那样,我该如何解决这个问题?scanf("%d",&a) >= 0;
答:
1赞
hanie
3/20/2020
#1
这不会检查返回的此检查,该检查是关于获取数据的成功和输入的数量。scanf("%d",&a) >= 0
a>=0
scanf
int main(void) {
int a,count,highest,lowest,range;
scanf("%d",&a);
for(count=0;a>= 0;count++){
if(count == 0){
highest = a;
lowest = a;
}
if(a > highest){
highest = a;
}
if(a < lowest){
lowest = a ;
}
scanf("%d",&a);
}
range = highest - lowest;
printf("%d\n %d\n %d\n %d\n",count,highest,lowest,range);
return 0;
}
2赞
Deepu
3/20/2020
#2
scanf()
C 中的函数返回成功扫描的输入总数,如果在分配第一个接收参数之前发生输入失败,则返回 EOF。因此,在您的情况下,即使您输入负数,也会返回该值。因此,在按 CTRL D 之前,代码中的循环不会终止。scanf("%d",&a)
1
for
3赞
Vlad from Moscow
3/20/2020
#3
按以下方式在 for 循环中编写条件
for ( count = 0; scanf("%d",&a) == 1 && a >= 0; count++ ){
//...
此外,最好将所有 if 语句组合成一组 if-else 语句,例如
if ( count == 0 ){
highest = a;
lowest = a;
}
else if( a > highest ){
highest = a;
}
else if(a < lowest){
lowest = a ;
}
评论
scanf