我正在学习C ++并在尝试使用公式计算当前时遇到了这个问题。
我得到了:0.628818
答案应该是:
f = 200 Hz
R = 15欧姆
C = 0.0001(100μF)
L = 0.01476(14.76mH)
E = 15 V
答案:I = 0.816918A(已计算)
以下是我的代码:
#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但似乎也无法正常工作。
答案 0 :(得分:1)
截断误差是指仅使用无穷级数的前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。
答案 1 :(得分:0)
主要问题是½乘以πfC而不是分割,这里:
(1.0 / 2.0 * PI*f*c)
使用合适的命名值可以最好地避免这类问题(这也可以让您使用更快,更精确的x*x
代替std::pow(x,2)
)。
你也可以使用标准的斜边函数而不是平方和sqrting内联来删除一些算术:
double ans = e / std::hypot(r, (2*PI*f*l - 0.5/PI/f/c));
#include <iostream>
#include <cmath>
int main()
{
static constexpr double PI = 4 * std::atan(1);
double r = 15; // ohm
double f = 200; // hertz
double c = 0.0001; // farad
double l = 0.01476; // henry
double e = 15; // volt
double current = e / std::hypot(r, (2 * PI*f*l - 0.5/PI/f/c));
std::cout << "I = " << current << "A" << std::endl;
}