0

I am very much a beginner to programming in C so please help out here. I am trying to write a program that loops asking the user to enter a number, if the number is positive it adds it to the total, and if it is negative it ends the program and displays the average, lowest input, and highest input. Unfortunately no matter what I change with the low and high things I keep getting 'nan' for the low, and whatever the negative number for the high.. please help!

#include<stdio.h>
int main(void)
{
    float input;
    float total;
    float low;
    float high;
    float average;
    int count=0;

    printf("\n\nPlease enter a positive number to continue or a negative number");
    printf(" to stop: ");

    scanf("%f", &input);

    while (input > 0)
    {
        count = count + 1;
        printf("\nPlease enter a positive number to continue or a negative");
        printf(" number to stop: ");
        scanf("%f", &input);
        total = total + input;  

        if ( low < input )
        {
            ( low = input );
        }
        else
        {
            ( low = low );  
        }
    }
    if (input < high)
    {
        (high = input);
    }
    else
    {
        (high = high);
    }

    average = total / count;
    printf("\n\n\nCount=%d",count);
    printf("\n\n\nTotal=%f",total);
    printf("\nThe average of all values entered is %f\n", average);
    printf("\nThe low value entered: %f\n", low);
    printf("\nThe highest value entered: %f\n", high);
    return 0;
}

After compiling it with gcc and testing it with the numbers 1, 5, 4, then -1 I get the following output

Count=3


Total=8.000000
The average of all values entered is 2.666667

The low value entered: nan 

The highest value entered: -1.000000
4

2 回答 2

0

你已经成为垃圾价值观的牺牲品——对于初学者来说这是一个常见的错误。具体来说,它发生在这些方面 -

float total;
float low;
float high;
float average;

当您编写它时,系统会为变量分配一个内存位置。计算机虽然不是无限的,所以它只是使用一个曾经被其他东西使用但不再被使用的内存位置。但大多数时候,“其他东西”不会自行清理(因为它会花费很多时间),所以那里的信息会留在那里,例如fdaba7e23f. 这对我们来说完全没有意义,所以我们称之为垃圾值。

您可以通过初始化变量来解决此问题,如下所示 -

float total=0;
float low;
float high;
float average=0;

请注意,您必须为低变量添加一些额外的逻辑。这是一种方法 -

printf("\n\nPlease enter a positive number to continue or a negative number");
printf(" to stop: ");

scanf("%f", &input);
low=input;
high=input;

while (input > 0)
....
....

如您所见,我只是复制了您的代码并在第一行之后添加了两行scanf.

于 2013-09-28T22:10:46.733 回答
0

一方面,我不知道你有没有注意到,你的计数和总数都搞砸了。

请更改执行顺序,除了@Drgin给出的初始化答案

int total = input;
while (input > 0)
{
 printf("\nPlease enter a positive number to continue or a negative");
 printf(" number to stop: ");
 scanf("%f", &input);
 count = count + 1;
 total = total + input;
于 2013-09-28T22:13:03.960 回答