我的程序创建的输出首先是准确的,然后在5000000以上的所有答案变成0。我想知道为什么这是这种情况,当我使用函数我称之为苍鹭的面积。三角形面积的浮点难度
#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;
}
这可能与使用浮点数的问题有关。为什么在最后一次输出500000后得到0的输出?
使用double来代替浮动 – seccpur
这个问题是众所周知的[解决方案在维基百科上](https://en.wikipedia.org/wiki/Heron%27s_formula#Numerical_stability) – harold