【问题标题】:Percentage calculation returns zero [duplicate]百分比计算返回零 [重复]
【发布时间】:2018-11-27 06:52:05
【问题描述】:
double calculatePercentage(int unmatched, int charLen){
    double percentageReturn = (((charLen - unmatched)/charLen) * 100);
    cout << "percenpercentageReturntage " << percentageReturn << endl;
    return percentageReturn;
}

我试图计算这些值的百分比,但它返回0。我尝试使用intfloatdouble,但都返回0

谁能帮我解决这个问题?

【问题讨论】:

  • 整数除法截断,(charLen - unmatched)/charLen 是整数除法。

标签: c++ math floating-point int double


【解决方案1】:

您可以在进行除法和乘法运算时对double 进行类型转换,以便整体结果将在double 中。你可以这样做:

double percentageReturn = ( ( (double)(charLen - unmatched) / (double)charLen ) * 100.0 );

【讨论】:

    【解决方案2】:

    在下面的语句中,首先计算赋值的右侧,然后分配给percentageReturn,此时会发生隐式转换(如果需要)。

    double percentageReturn = (((charLen - unmatched)/charLen) * 100);
    

    右边所有参数都是整数,所以会是整数除法,然后是截断结果。

    由于(charLen - unmatched) 将小于charLen,因此截断结果将为0。

    要解决此问题,您可以将除法的分子或分母转换为 double,这将使您得到不截断的除法。

    (double)(charLen - unmatched)(double)charLen

    【讨论】:

      【解决方案3】:

      C++ 中的除法运算符/,当它的两边都是整数类型时执行一个整数除法。为了克服这个问题,您需要先将参数转换为浮点类型,如下所示:

      double cl = static_cast<double>(charLen);
      double um = static_cast<double>(unmatched);
      

      请注意,如果您使用的是现代 C++,最好使用 static_cast 强制转换隐式可转换类型,而不是旧的 C 样式强制转换。

      【讨论】:

        【解决方案4】:

        要解决您的问题,请尝试这两种可能的解决方案之一

        #include <stdio.h> 
        #include <iostream>
        #include <math.h>
        using namespace std;
        double calculatePercentage(int unmatched, int charLen) {
            double percentageReturn = (((double)(charLen - unmatched) / (double)charLen) * 
        100);
            cout << "percenpercentageReturntage_int " << percentageReturn << endl;
        
            return percentageReturn;
        }
        double calculatePercentage(double unmatched, double charLen) {
            double percentageReturn = (((charLen - unmatched) / charLen) * 100);
            cout << "percenpercentageReturntage_double " << percentageReturn << endl;
            return percentageReturn;
        }
        
        int main()
        {
        
            cout << "the integer function  value is :" << calculatePercentage(4, 50) << endl;
            cout << "the double function  value is :" << calculatePercentage((double)4, 
        (double)50) << endl;
        
            return 0;
        }
        

        【讨论】:

          猜你喜欢
          • 2014-08-23
          • 2018-08-04
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2013-05-05
          • 2012-09-05
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多