我需要为我的C编程类创建一个程序,允许用户使用未知数量的数字输入。然后它将获取这些值并找到最小值,最大值和平均值。
以下是我到目前为止编写的源代码:
#include <stdio.h>
#include <stdlib.h>
//Post-Lab #4
int main()
{
int sums = 0;
int n = 0;
int number;
int min = number; //Lines 6 to 12 define the variables being used in this program.
int max = number;
int avg;
char confirm = 'Y'; //Using this to end the while loop under user influence.
printf("NOTE: Program will continue to receive inputs until user states 'N'. \n");//a negative value ends the while loop.
printf("Please enter a value: ");
scanf(" %d", &number);
printf(" %d, %d, %d, %d, %d", number, min, max, n, sums);//Im using these print command to troubleshoot what the values look like after a step.
while (number >= 0) //Utilizing while loop to allow user multiple, in this case, numerical inputs.
{
printf("Would you like to enter another value (Y/N): ");
scanf(" %c", &confirm);
if(confirm == 'Y') //Had to nest another if statement. Program was including negative value.
{
printf("Please enter a value: "); //Prints guide for user.
scanf(" %d", &number); //Used to read user inputs
n = n + 1; //Counter to use for finding the average later in the program.
sums = sums + number; //Since this program cannot use arrays, these values will not be stored, but simply added.
if (number > max) //If statement used to determine the maximum value as the user enters them.
{
max = number;
}
if (number < min)
{
min = number;
}
printf(" %d, %d, %d, %d, %d", number, min, max, n, sums);
}
else
break;
}
avg = sums / n; //Calculates the average.
printf("Your results are: \n");
printf("The maximum value is: %d \n", max); //Lines 41 to 44 simply print the results of the calculation.
printf("The minimum value is: %d \n", min);
printf("The average is: %d \n", avg);
return 0;
}
我的问题发生在第8到第17行
当我在第16行上为用户输入scanf
时,它会将number
变量设置为该值,但不会将变量max
和min
设置为该输入。 />
它等于2686868
。我该如何解决这个问题?
答案 0 :(得分:1)
你的代码行下面是错误的。
int min = number; //Lines 6 to 12 define the variables being used in this program.
int max = number;
由于number
未初始化,请在输入数字后输入。
printf("Please enter a value: ");
scanf(" %d", &number);
int min = number; //Have These Lines Here
int max = number;
就像其中一条评论告诉您更改不传播,变量保留它们设置的值,直到稍后更改为止,更改number
不会更改min
和{{1}自动。