C 编程 nan 输出

标签 c output nan

我是 C 编程的初学者,所以请在这里帮忙。我正在尝试编写一个程序,循环要求用户输入一个数字,如果数字为正数,则将其添加到总数中,如果数字为负数,则结束程序并显示平均值、最低输入和最高输入。不幸的是,无论我如何改变低值和高值,我总是得到低值的“nan”,无论高值的负数如何..请帮忙!

#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;
}

使用 gcc 编译并使用数字 1、5、4 和 -1 进行测试后,我得到以下输出

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

最佳答案

您已成为垃圾值的受害者 - 这是初学者的常见错误。具体来说,它发生在这些行中 -

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

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

您可以通过初始化变量来解决这个问题,就像这样 -

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

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

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 之后添加了两行。

关于C 编程 nan 输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19072147/

相关文章:

c - 链表 , 数据结构 , 结构

比较c中不同文本文件的字符串

c - 如何使用预处理器删除全局数组?

javascript - 使用csv-parser解析csv后如何获取输出?

floating-point - 安静 NaN 和信号 NaN 有什么区别?

python - 查找生成 NaN 的计算

python - Pandas - 检查系列中的所有值是否都是 NaN

c - (C) Scanf - 输入每次都为 0

javascript - Angular 2 @Input - 如何从父组件绑定(bind)子组件的 ID 属性?

bash - 将 Fortran 程序输出到变量中