C++直角三角形判定程序浮点数精度异常求助
问题排查与修复
先看你这段代码的核心问题:
1. round函数调用完全无效
你写了round(aSquared);这类语句,但round函数是返回四舍五入后的结果,不会直接修改原变量。必须把返回值重新赋值给对应的变量,比如:
aSquared = round(aSquared); bSquared = round(bSquared); cSquared = round(cSquared);
不然原来的平方值根本没变化,等于白调用了round。
2. 浮点数直接用==比较的精度陷阱
就算修正了round的调用,浮点数本身的存储精度问题还是会坑你。比如1.4142作为float存储时,实际值和真实的√2有微小误差,平方后也不会精确等于2。直接用==比较两个浮点数,哪怕差一点点都会判定为不相等。
正确的做法是:判断两个值的差的绝对值是否小于一个极小的阈值(比如1e-4,可根据需求调整),只要误差在这个范围内,就认为它们相等。
修改后的完整代码
#include <iostream> #include <cmath> // 必须包含round和fabs的头文件 using namespace std; void isRight(float sideA, float sideB, float sideC){ float aSquared = sideA * sideA; float bSquared = sideB * sideB; float cSquared = sideC * sideC; // 修正round调用,将四舍五入结果赋值回原变量 aSquared = round(aSquared); bSquared = round(bSquared); cSquared = round(cSquared); // 用阈值判断,规避浮点数精度误差 const float eps = 1e-4; if (fabs(aSquared + bSquared - cSquared) < eps || fabs(cSquared + bSquared - aSquared) < eps || fabs(aSquared + cSquared - bSquared) < eps){ cout << "This is a right triangle" << endl; } } int main() { float sideA, sideB, sideC; cout << "Enter the lengths of the three sides of a triangle -- "; cin >> sideA >> sideB >> sideC; isRight(sideA,sideB,sideC); }
另外注意:原代码里main函数最后多了一个单独的},要删掉,否则编译会报错。
内容的提问来源于stack exchange,提问作者confusedPro
相关产品推荐
相关产品推荐

