关于C中的float数据类型

时间:2015-06-29 16:52:53

标签: c floating-point

我正在用C学习逻辑构建,我只是写一个关于方程的小代码。这是代码:

#include<stdio.h>

int main()
{
    float a,b;

    printf("Find solutions for equation: aX + b = 0\n");
    printf("Input value for a: ");
    scanf("%f", &a);
    printf("Input value for b: ");
    scanf("%f", &b);

    if(a == 0)
    {
        if (b ==0)
        {
            printf("Countless solution.");
        }
        else
        {
            printf("Have no solution.");
        }
    }

    else
    {
        printf("Have one solution: x = %.2f", -b/a);
    }

}

问题是当我输入a =任意数字,b = 0时,我的解决方案是:x = -0.00。

我不明白为什么x = -0.00代替x = 0.00? 我测试了案例a==0 && b==0a==0 && b!=0,但它运行正常。 我对此感到困惑。有谁可以向我解释一下?

3 个答案:

答案 0 :(得分:3)

浮点数的IEEE标准表示允许负0.基本上,有一位表示浮点数的“符号”。当你翻转那个位时,标志就会被翻转。在您的示例中,当您使用值var customers = new List<Tuple<int, string>>(); // the list of ID, Name using (var con = new SqlConnection("your connection string")) { using(SqlCommand cmd = new SqlCommand("select ID, Name from Customer", con)) { con.Open(); using(SqlDataReader reader = cmd.ExecuteReader()) { while (reader.Read()) { customers.Add(new Tuple<int, string>( (int)reader["ID"], reader["Name"].ToString())); } } } } // Store customers to file 时,使用的值为-b,其符号位会被翻转。其符号位翻转的b0

答案 1 :(得分:1)

代码正常运行。许多浮点类型支持+-零。

要避免打印-0.0,请添加0.0

printf("Have one solution: x = %.2f", -b/a + 0.0);

答案 2 :(得分:0)

问题的简要概述是:

浮点数的精度仅限于浮点类型中的位数。因此,将任何浮点运算的结果赋给变量将给出一个非常非常接近的近似值,但不是一个确切的数字。

因此,IEEE标准规定浮点数使用带符号的零表示。虽然这些值精确为零,但是有符号的变量可以比作接近零的单侧限制(这样一个限制可以精确为零,但任何无限小的值都会有一个符号)。

C表示法“-b”与“-1 * b”相同,因此如果a为正,b为正签名版本0,则结果为该操作将为零的负面签名版本。