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



我得到:0.628818答案应该是:


  f = 200赫兹
  
  R = 15欧姆
  
  C = 0.0001(100µF)
  
  L = 0.01476(14.76mH)
  
  E = 15伏
  
  答案: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,但似乎也不起作用。

最佳答案

截断误差是指仅使用无限序列的前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;
}


只是开个玩笑。

08-26 18:49
查看更多