math.h中的错误

时间:2013-08-26 14:50:13

标签: c++ c pow math.h

我在C中遇到这个错误,只是无法弄清楚出了什么问题。以下查询构成了我的代码的一个组成部分,用于在连续迭代中以指数方式递增值。这是我编程的公式:

我已经评论了代码中的错误。

#include <math.h>
#include <iostream>

int main()
{
    double maxMeshS = 0;
    double minMeshS = 0;

    cout << "enter max mesh size (m): ";
    cin >>maxMeshS;

    cout <<"\nenter min mesh size (m): ";
    cin >> minMeshS;

    double raise = maxMeshS/minMeshS; //Values used for run maxMeshS = .5
    double factor = 1/9;              //                    minMeshS = .005    

    double b = pow(raise,factor);
    cout << "b " << b << endl;  // The error happens here when I use above values
                               // b comes out to be 1 which should be 1.668100 instead
    double a = minMeshS/b;
    cout << "a " << a << endl;

    int x;
    cout << "enter x " ;
    cin >> x;

    double queryCube = a*pow(b,x);
    cout << queryCube << endl;
    return(0);
}

然而,当我使用除maxMeshS/minMeshS的计算值,即100和1/9即.11111时,我获得b = pow(100, .1111) = 1.66800的正确值。为什么会这样?

2 个答案:

答案 0 :(得分:9)

你的因素是(int)1 / (int)9(int)0;几乎任何提升到第零级的力量都是一个 你可以做这样的事情

double factor = 1/9.0; // make sure the 9 is a floating point

答案 1 :(得分:6)

如果我没有记错,你必须将因子改为

double factor = 1.0/9;

问题在于编译器确实将1/9视为整数除法,结果为0。 所以你计算零的幂,它总是1。