为什么a + = b * pow(10,c-i-1)== 99 c ++? [英] Why a+=b*pow(10,c-i-1) == 99 c++?

查看:176
本文介绍了为什么a + = b * pow(10,c-i-1)== 99 c ++?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我写了这段代码,第一次循环结果是99.为什么结果99应该是100?

I wrote this code and first time of loop result is 99. Why is result 99, when it should be 100?

#include <iostream>
#include<math.h>
using namespace std;
int main ()
{
  int skt = 0;
  int sk[3];
int nsk = 3;
sk[0]=1;
sk[1]=2;
sk[2]=8;
for (int i=0; i<nsk; i++)
{
    skt = skt + (sk[i]*pow(10.0,nsk-i-1));
    cout <<" "<<skt<<endl;
}

}

此代码的结果

   99
   119
   127

,但是如果我使用库cmath,那是正确的答案

,but if I use library cmath it is correct answer

#include <iostream>
#include<cmath>
using namespace std;
int main ()
{
  int skt = 0;
  int sk[3];
int nsk = 3;
sk[0]=1;
sk[1]=2;
sk[2]=8;
for (int i=0; i<nsk; i++)
{
    skt = skt + (sk[i]*pow(10.0,nsk-i-1));
    cout <<" "<<skt<<endl;
}

}

此代码的结果

    100
    120
    128

有人可以解释为什么吗?

Could anybody explain why?

推荐答案

. com

from this link cplusplus.com

此标头(cmath)中提供了其他重载,用于算术类型的其他组合(Type1和Type2):这些重载在计算之前将其参数有效地转换为double,除非至少一个参数的类型为long double(在这种情况下,两者都将强制转换为long double.

Additional overloads are provided in this header ( cmath ) for other combinations of arithmetic types (Type1 and Type2): These overloads effectively cast its arguments to double before calculations, except if at least one of the arguments is of type long double (in which case both are casted to long double instead).

我敢打赌,如果您使用它,那么在math.h中是正确的

I bet if you cast it it would be correct in math.h

这篇关于为什么a + = b * pow(10,c-i-1)== 99 c ++?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆