【发布时间】:2026-02-11 15:30:01
【问题描述】:
我需要帮助来修复我的代码。我的代码要求用户多次输入一个数字,并在输入 -1 后终止程序。然后,将得到 Sum、Max、Min、Average 和 Median 值。
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