我需要为我的 C 编程类(class)创建一个程序,允许用户输入未知数量的数字。然后它将获取这些值并找到最小值、最大值和平均值。
下面是我迄今为止编写的源代码:
#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
。我该如何解决这个问题?
最佳答案
下面的代码行是错误的。
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
并且自动最大
。
关于c - 变量值不存储,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42029412/