gpt4 book ai didi

C++ 截断错误?

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

我正在学习 C++,在尝试使用公式计算电流时遇到了这个问题。

formula

我得到:0.628818 答案应该是:

f=200 Hz

R=15 Ohms

C=0.0001 (100µF)

L=0.01476 (14.76mH)

E = 15 V

Answer: I = 0.816918A (calculated)

下面是我的代码:

#include <iostream>
#include <cmath>

int main()
{
const double PI = 3.14159;
double r = 15;
double f = 200;
double c = 0.0001;
double l = 0.01476;
double e = 15;

double ans = e / std::sqrt(std::pow(r, 2) + (std::pow(2 * PI*f*l - (1.0 / 2.0 * PI*f*c), 2)));

std::cout << "I = " << ans << "A" << std::endl;
}

我已阅读有关截断错误的信息并尝试使用 1.0/2.0,但似乎也不起作用。

最佳答案

截断误差是指仅使用无穷级数的前 N ​​项来估计一个值。所以你的问题的答案是“否”。但是,您可能会发现以下内容有些有趣......

#include <iostream>
#include <cmath>
#include <iomanip>

using namespace std;

template<typename T>
T fsqr(T x) { return x * x; }

// Numerically stable and non-blowuppy way to calculate
// sqrt(a*a+b*b)
template<typename T>
T pythag(T a, T b) {
T absA = fabs(a);
T absB = fabs(b);
if (absA > absB)
{
return absA*sqrt(1.0 + fsqr(absB / absA));
} else if (0 == absB) {
return 0;
} else {
return absB*sqrt(1.0 + fsqr(absA / absB));
}
}
int main () {

double e, r, f, l, c, ans;

const double PI = 3.14159265358972384626433832795028841971693993751058209749445923078164062862089986280348253421170;
cout << "Insert value for resistance: " << endl;
cin >> r ;

cout << "Insert value for frequency: " << endl;
cin >> f;

cout << "Insert value for capacitance: " << endl;
cin >> c;

cout << "Insert value for inductance: " << endl;
cin >> l;

cout << "Insert value for electromotive force (voltage): " << endl;
cin >> e;

ans = e / pythag(r, 2*PI*f*l - (1/(2*PI*f*c)) );

cout << "I = " << ans << "A" << endl;

system("pause");

return 0;
}

关于 PI 开个玩笑。

关于C++ 截断错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49361739/

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