gpt4 book ai didi

c++ - 代码块 C++ 错误

转载 作者:行者123 更新时间:2023-11-28 02:26:04 25 4
gpt4 key购买 nike

我正在用 C++ (CodeBlocks) 做一些事情,但我发现了一个奇怪的问题。我将我的代码发送给了我的 friend (他在 DevC++ 中对其进行了测试)并且成功了。我试过这两个代码:

#include <iostream>
#include <math.h>
using namespace std;

int main() //this function works
{
if (pow(3, 2) + pow(4, 2) == pow(5, 2)) {
cout << "Works" << endl;
} else { cout << "Nope" << endl; }
}

但是,然后我像这样更改了 main 函数(但它不起作用):

int main() //this function doesn't work
{
int t1 = 3, t2 = 4, t3 = 5;
if (pow(t1, 2) + pow(t2, 2) == pow(t3, 2)) {
cout << "Works" << endl;
} else { cout << "Doesn't work" << endl; }
}

谁知道问题出在哪里?

最佳答案

除非你告诉我们你的“奇怪”错误是什么,否则我假设你的第二个代码片段打印:

Doesn't work

问题是,您正在比较 float ,因为 pow() 返回 float see the definition of pow() function .

由于 Rounding Errors, float 学并不精确.像 9.0 这样的简单值无法使用二进制 float 来精确表示,而且 float 的精度有限意味着运算顺序的微小变化都会改变结果。不同的编译器和 CPU 架构以不同的精度存储临时结果,因此结果会因环境的细节而异。例如:

    float a = 9.0 + 16.0
float b = 25.0
if(a == b) // can be false!
if(a >= b) // can also be false!

甚至

    if( Math.abs(a-b) < 0.00001) // wrong - don't do this

这是一种糟糕的方法,因为选择固定的 epsilon (0.00001) 因为它“看起来很小”,当被比较的数字也非常小时,它实际上可能太大了。

我个人使用下面的方法,

public static boolean nearlyEqual(float a, float b, float epsilon) {
final float absA = Math.abs(a);
final float absB = Math.abs(b);
final float diff = Math.abs(a - b);

if (a == b) { // shortcut, handles infinities
return true;
} else if (a == 0 || b == 0 || diff < Float.MIN_NORMAL) {
// a or b is zero or both are extremely close to it
// relative error is less meaningful here
return diff < (epsilon * Float.MIN_NORMAL);
} else { // use relative error
return diff / Math.min((absA + absB), Float.MAX_VALUE) < epsilon;
}
}

并且不要忘记阅读What Every Computer Scientist Should Know About Floating-Point Arithmetic !

引用: This是我回答的引用。

编辑: 由于 OP 的问题涉及 C++,所以这里是 nearlyEqual() 的编辑版本:

#include <iostream>     // std::cout
#include <cmath> // std::abs
#include <algorithm> // std::min
using namespace std;

#define MIN_NORMAL 1.17549435E-38f
#define MAX_VALUE 3.4028235E38f

bool nearlyEqual(float a, float b, float epsilon) {
float absA = std::abs(a);
float absB = std::abs(b);
float diff = std::abs(a - b);

if (a == b) {
return true;
} else if (a == 0 || b == 0 || diff < MIN_NORMAL) {
return diff < (epsilon * MIN_NORMAL);
} else {
return diff / std::min(absA + absB, MAX_VALUE) < epsilon;
}
}

int main(void) {
float t1 = 3.0, t2 = 4.0, t3 = 5.0, epsilon = 0.0000000001; // don't use int here!
if (nearlyEqual((pow(t1, 2) + pow(t2, 2)), pow(t3, 2), epsilon)) {
cout << "Works" << endl;
} else {
cout << "Doesn't work" << endl;
}
return 0;
}

输出是:

Works

编译器: Cygwin C++ 编译器。

Cygwin 版本:1.7.25

关于c++ - 代码块 C++ 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30628945/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com