【问题标题】:C I/O Scanning and Printing w/ Sentinels带 Sentinel 的 C I/O 扫描和打印
【发布时间】:2014-03-17 17:50:48
【问题描述】:

我有一个包含一堆数字的输入文件,例如:

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", &current);
     if(current < low){
       low = current;}
     else if(current > high){
       high = current;}
   }
  printf("High: %i   Low: %i \n",high,low);
  }

现在我希望能够删除最高和最低并打印出其他数字。我的问题是,尝试使用哨兵值解决这个问题是否明智?制作一个循环的打印语句,如果命中了哨兵值,它什么也不打印?

【问题讨论】:

  • 为了更好地解决这个问题,需要说明如何处理不是最小值/最大值的重复值,如何处理最小值/最大值的重复值。打印的订单是否需要与输入的订单相匹配?

标签: c printing io scanf sentinel


【解决方案1】:

处理列表两次。首先寻找低/高。下次,如果不是低/高,则打印。

使用\n 作为指示输入结束的信号是一个问题,因为\nscanf("%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", &current, &n) == 1) {
    if (current < low) {
      low = current;
    }
    if (current > high) {
      high = current;
    }
    p += n;
  }
  p = buffer;
  while (sscanf(p, "%i%n", &current, &n) == 1) {
    if ((current != low) && (current != high)) {
      printf("Other: %i\n", current);
    }
    p += n;
  }
printf("High: %i   Low: %i\n", high, low);
return 0;
}

【讨论】:

    【解决方案2】:

    试试这个,

    #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", &current);
    
         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
    }
    

    【讨论】:

      猜你喜欢
      • 2013-01-09
      • 1970-01-01
      • 1970-01-01
      • 2019-07-27
      • 2018-02-08
      • 1970-01-01
      • 1970-01-01
      • 2023-03-10
      • 1970-01-01
      相关资源
      最近更新 更多