首页 > 解决方案 > 如何防止系统将标记值作为输入?

问题描述

所以,我创建了一个简单的程序供用户输入温度并计算最高、最低、平均值。在用户输入哨兵值停止循环后,不知何故哨兵值也会被当作输入并弄乱数据,这是我的代码,如果你有时间请帮我看看,非常感谢

#include <stdio.h>

int main()
{
    int temperature, highest = 0, lowest = 0, counter = 1, counter2 = 0, total = 0;
    float average;
    
    printf("Enter temperature (-999 to stop) > ");
    scanf("%d", &temperature);
    
    if (temperature == -999) {
    printf("No temperature is captured.");
    return 0;
    }
    
    else if (temperature > 40)
    counter2++;
    
    do {
        printf("Enter temperature (-999 to stop) > ");
        scanf("%d", &temperature);
        
        if (temperature >= highest)
        highest = temperature;
        
        if (temperature <= lowest)
        lowest = temperature;
        
        if (temperature > 40)
        counter2++;
        
        total += temperature;
        counter++;
    } while (temperature != -999);
    
    average = total / counter;
    
    printf("Total days with temperature more than 40'C > %d\n", counter2);
    printf("The lowest temperature  > %d\n", lowest);
    printf("The highest temperature > %d\n", highest);
    printf("Average of temperature  > %.2f\n", average);
}

标签: cloopssentinel

解决方案


您的代码过于复杂。为什么你有循环外的第一个温度输入?第一个输入没有什么特别之处。

你想要这样的东西:

#include <stdio.h>

int main()
{
  int temperature, highest = 0, lowest = 0, counter = 1, counter2 = 0, total = 0;
  float average;

  do {
    printf("Enter temperature (-999 to stop) > ");
    scanf("%d", &temperature);

    if (temperature == -999)
      break;

    if (temperature >= highest)
      highest = temperature;

    if (temperature <= lowest)
      lowest = temperature;

    if (temperature > 40)
      counter2++;

    total += temperature;
    counter++;
  } while (temperature != -999);

  average = total / counter;

  printf("Total days with temperature more than 40'C > %d\n", counter2);
  printf("The lowest temperature  > %d\n", lowest);
  printf("The highest temperature > %d\n", highest);
  printf("Average of temperature  > %.2f\n", average);
}

仍然存在一些错误,如果您根本不输入温度,程序将无法正常运行。但我让你自己。应该不会太难。


推荐阅读