gpt4 book ai didi

c++ - 带 abs() 的方程给出了错误的答案 (gcc/g++)

转载 作者:行者123 更新时间:2023-12-05 08:24:44 25 4
gpt4 key购买 nike

不知何故,我从涉及库函数 abs() 的等式中得到了错误的结果。这是我存在问题的代码:

main.cpp ------------------------------------

#include <iostream>
#include <cmath>

#include "test999.h"

using namespace std;

int main()
{
float n = 11;
ak r;

r = test(n);
printf("\n");
for(int i = 0; i < n; i++){
printf("r.yp[%d] = %3.7f \n", i, r.yp[i]);
}

return 0;
}

test999.h --------------------------------------

struct ak{
float yp[20];
};

ak test(int n){

float u[] = {0, 0, 0, 0, 0, 0, 0, 0.5, 4.5, 35, 10, 25, 40, 55};
ak r;
float a, b;

for(int i = 0; i < n; i++){
a = abs(u[i+3] - u[i+2]);
b = abs(u[i+1] - u[i]);

printf("i = %d a = u[%d](%2.4f) - u[%d](%2.4f) = %2.4f \n b = u[%d]-u[%d] = %2.4f (%2.4f - %2.4f) \n", i, i+3, u[i+3], i+2, u[i+2], a, i+1, u[i+1], i, u[i], b);

if ((a+b) != 0.0f){
r.yp[i] = (a * u[i+1] + b * u[i+2]) / (a+b);
}
else{
r.yp[i] = (u[i+2] + u[i+1]) / 2.0f;
}
printf("yp[%d] = %2.4f \n\n", i, r.yp[i]);
}
return r;
}

它导致 abs(0.5)-0.0(案例 i=4)和 abs(35.0)-4.5(案例 i=6)等式的错误值:

enter image description here

改变方程以使用 std::abs() 计算正确:

enter image description here

如果我将所有内容都移至 main.cpp 模块,那么这两种情况都有效,仅仅是因为我编写了缺陷代码......或者从 0.5 到 0.0 的四舍五入发生在我应该考虑的地方......?

最佳答案

std::abs(int)std::abs(float)。前者继承自C abs(int)。在 C 中没有浮点重载,它被称为 fabs(也可用作 std::fabs)。

您在 using namespace std; 上绊倒了,混淆了实际调用的函数。请注意,您将它放在 main 中,但不在 header 中,这实际上很好,但它在 main 中仍然有害,因为一旦将所有代码放在 中>main,突然调用了一个不同的函数。没有 using namespace std;abs(some_float) 调用 ::abs(int)。通过 using namespace std;abs(some_float) 调用 std::abs(float)

请注意,允许但不保证从 C 继承的 header 在全局命名空间中引入名称,因此您也可能会遇到编译器错误。

abs 替换为 std::abs 并删除 using namespace std。出于更多不从 std 中提取所有名称的原因,我建议您引用 Why is "using namespace std;" considered bad practice?

关于c++ - 带 abs() 的方程给出了错误的答案 (gcc/g++),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73446020/

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