📜  C,C++和Java的浮点运算和关联性

📅  最后修改于: 2021-05-30 11:27:32             🧑  作者: Mango

浮点运算是否遵循关联性?换句话说,对于表达式“(A + B)+ C”和“ A +(B + C)”,我们是否总是得到相同的结果

人们可能希望浮点数在编程语言中遵循数学上的关联性,因此遵循编程语言中的关联性规则。但是,并非在所有情况下都是如此。

考虑下面的C / C++程序。

// C/C++ program to demonstrate that floating point
// addition may not be associative.
#include
int main()
{
    // A and B have sane values but apposite signs
    float A = -500000000;
    float B =  500000000;
  
    float C = 1;
  
    printf("A + (B + C) is equal to %f \n", A + (B + C));
    printf("(A + B) + C is equal to %f", (A + B) + C);
  
    return 0;
}

输出:

A + (B + C) is equal to 0.000000 
(A + B) + C is equal to 1.000000

从以上给出的输出中可以明显看出,浮点算法可能并非在每种情况下都遵循关联律。这是由于存储和表示浮点数的格式,在计算过程中它会四舍五入,因此,代数的关联定律不一定适用于浮点数。在这种情况下,

Explanation for above output:

A + (B + C):
(B + C) = 500000000.0 + 1.0
        = 500000000.0 
(rounded off during floating point arithmetic)

A + (B + C) = -500000000.0 + 500000000.0 
            =  0.000000

(A + B) + C:
(A + B) = -500000000.0 + 500000000.0 
        = 0.000000

(A + B) + C = 0.000000 + 1 
            = 1.000000

Java怎么样?
我们在Java获得相同的结果,因为Java对浮点数也使用类似的表示形式。

// Java program to demonstrate that floating point
// addition may not be associative
import java.io.*;
  
class Main
{
    public static void main (String[] args)
    {
        // A and B have sane values but apposite signs
        float A = -500000000;
        float B =  500000000;
  
        float C = 1;
  
        System.out.println("A + (B + C) is equal to " + 
                          (A + (B + C)));
        System.out.println("(A + B) + C is equal to " + 
                          ((A + B) + C));
    }
}

输出:

A + (B + C) is equal to 0.000000 
(A + B) + C is equal to 1.000000

整数呢?
现在,当数据类型为整数时,让我们尝试相同的计算。这是一段代码供您观察:

#include
#include
int main()
{
   // A and B have sane values but apposite signs
   int A = -500000000;
   int B =  500000000;
  
   int C = 1;
  
   printf(" A + (B + C) is equal to %d \n", A + (B + C));
   printf("(A + B) + C is equal to %d", (A + B) + C);
  
   return 0;
}

输出:

A + (B + C) is equal to 1 
(A + B) + C is equal to 1
要从最佳影片策划和实践问题去学习,检查了C++基础课程为基础,以先进的C++和C++ STL课程基础加上STL。要完成从学习语言到DS Algo等的更多准备工作,请参阅“完整面试准备课程”