我有一个带有一堆数字的输入文件,例如:
3 7 10 21 8 4 9 2
我写了一些代码来记录最高和最低值:
#include<stdio.h>
main(){
int low;
int high;
int current;
char c;
scanf("%i", &low);
scanf("%i", &high);
while((c=getchar())!= '\n'){
scanf("%i", ¤t);
if(current < low){
low = current;}
else if(current > high){
high = current;}
}
printf("High: %i Low: %i \n",high,low);
}
现在我希望能够删除最高和最低,并打印出其他数字。我的问题是,尝试使用哨兵值解决这个问题是明智的吗?制作一个循环的打印语句,如果命中了sentinel值,它只打印什么?
答案 0 :(得分:1)
两次处理清单。首先寻找低/高。下次打印,如果不是低/高。
使用\n
作为指示输入结束的信号是一个问题,因为\n
是scanf("%i"...
静默消耗的空白区域。最好用fgets()
检查sscanf()
的结果是个好主意。
前两个数字可能不是低/高顺序。
使用"%n"
跟踪buffer
的进度。
#include <ctype.h>
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <limits.h>
int main() {
int low = INT_MAX;
int high = INT_MIN;
int current;
char buffer[1000];
fgets(buffer, sizeof buffer, stdin);
char *p = buffer;
int n;
while (sscanf(p, "%i%n", ¤t, &n) == 1) {
if (current < low) {
low = current;
}
if (current > high) {
high = current;
}
p += n;
}
p = buffer;
while (sscanf(p, "%i%n", ¤t, &n) == 1) {
if ((current != low) && (current != high)) {
printf("Other: %i\n", current);
}
p += n;
}
printf("High: %i Low: %i\n", high, low);
return 0;
}
答案 1 :(得分:0)
试试这个,
#include<stdio.h>
main(){
int low;
int high;
int current;
char c;
scanf("%i", &low);
scanf("%i", &high);
int val;
do {
printf("Enter a number:");
scanf("%d", ¤t);
if(current < low){
val=low;
low=current;
current=val;
}
else if(current > high){
val=high;
high=current;
current=val;
}
printf("%i\n",current); //prints the value if it is in between
}while((c=getch())!='\n');
printf("High: %i Low: %i \n",high,low);//can remove if it this is not required
}