gpt4 book ai didi

c++ - 三角形区域的浮点难度

转载 作者:搜寻专家 更新时间:2023-10-31 02:14:43 26 4
gpt4 key购买 nike

我的程序创建的输出最初是准确的,然后对于所有超过 5000000 的答案都变为 0。我想知道为什么当我使用我称为 Heron's Area 的函数时会出现这种情况。

#include "stdafx.h"
#include "stdlib.h"
#include <iostream>
#include <math.h>
#include <stdio.h>

float heron_area(float a, float c) {
float s = (a + a + c) / 2.0f;
return (s - a)*sqrtf(s*(s - c));
}


int main(void) {
int j = 18;
float i = 10;
for (int k = 0; k < j; k++){
float g = i * 10;
std::cout << heron_area(g, 1) << std::endl;
i = g;
}


return 0;
}

这可能与使用 float 的问题有关。为什么我在最后输出 500000 后得到 0 的输出?

最佳答案

正如您所怀疑的那样,这是 float 的问题。

如果你在 heron_area 中打印 as,你会注意到它们很快变得相同,使 s -一个零。

这发生在 c 远小于 a 时(也就是说,当你有一个非常“尖”的三角形时;你的零出现在两侧为 10,000,000 且第三个是 1)。

将类型更改为 double 会使问题稍后出现,但不会消失。

如果你想处理非常大的幅度差异,你需要重新安排你的计算。

Wikipedia 上有一个解决方案(在评论中由@harold 链接)给出

Area = 0.25 * sqrt((a+(b+c)) * (c-(a-b)) * (c+(a-b)) * (a+(b-c)))

其中 a >= bb >= c,括号是必需的。
是的,您需要担心操作顺序。

(还有一篇非常详细的文章 here 对此解决方案进行了分析。)

关于c++ - 三角形区域的浮点难度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39589272/

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