【问题标题】:C Programming - Getting the Median from User InputsC 编程 - 从用户输入中获取中位数
【发布时间】:2026-02-11 15:30:01
【问题描述】:

我需要帮助来修复我的代码。我的代码要求用户多次输入一个数字,并在输入 -1 后终止程序。然后,将得到 Sum、Max、Min、AverageMedian 值。

Sum、Min 和 Max 似乎工作正常。但在“平均值”上,它会将 -1 视为用户输入,此外,我需要有关如何获得中值的帮助。

这是我目前得到的。

#include <stdio.h>

int main(){
char name[30];
int userInput;
int count = 0;
int sum = 0; // changed from 1 to 0
int max, min = 1000;
float average;

printf("Please enter your name: ");
scanf("%s", &name);

printf("Hello, %s, ", name);

do {
printf("Enter an integer (-1 to quit): ");
scanf("%d", &userInput);

if (userInput == -1) break; // I added this line, average works fine now

sum = sum + userInput;
count = count + 1;
average = sum / count;

if (userInput > max){
max = userInput;
}

if (userInput < min && userInput >= 0){
min = userInput;
}

}
while (userInput >= 0);

printf("Sum: %d \n", sum);
printf("Average: %.2f \n", average);
printf("Max: %d \n", max);
printf("Min: %d \n", min);

return 0;

}

这是我的示例输出:

Please enter your name: A
Hello, A, Enter an integer (-1 to quit): 10
Enter an integer (-1 to quit): 20
Enter an integer (-1 to quit): 10
Enter an integer (-1 to quit): -1
Sum: 40
Average: 10.00
Max: 20
Min: 10

所以除了获得中值之外,其余部分似乎在经过一些修改后现在可以工作了。

【问题讨论】:

  • if(userInput == -1) break;

标签: c


【解决方案1】:

您不想在 userInput == -1 时增加计数

【讨论】:

    【解决方案2】:

    在检查 userInput == -1 是否为之前,您将增加 count 并添加到总和。尝试重写你的循环:

    while(1){
      printf("Enter an integer (-1 to quit): ");
      scanf("%d", &userInput);
      if(userInput == -1)
        break;
    /* rest of loop body goes here */
    }
    

    【讨论】: