C++ 整除 1/2 得什么

 

今天改一段小代码,发现怎么改都没用,公式重推了一遍,还是没问题。后来发现是整除忘了转换类型了:

        printf("=======================\n");
        printf("=======================\n");
        printf("=======================\n");
double aaaaa;
double bbbbb;
aaaaa=1/2;

        printf("1/2 is= %.8le\n\n",aaaaa);
bbbbb=0.5;

        printf("0.5 is = %.8le\n\n",bbbbb);


        printf("=======================\n");
        printf("=======================\n");
        printf("=======================\n");

后来快放弃的时候才发现,原来是整数类型和浮点型不通,整数除以整数得整数,也就是说 1/3 得零,2/3 也得零

于是测试输出:

=======================
=======================
1/2 is= 0.00000000e+00

0.5 is = 5.00000000e-01

=======================
=======================
=======================

因此尽量避免 整数除以整数,比如说改成:

1.0/2
或者:
1.0/2.0

变量的话,可以使用强制类型转换:

#include <stdio.h>

main()
{
   int sum = 17, count = 5;
   double mean;

   mean = (double) sum / count;
   printf("Value of mean : %f\n", mean );

}

当上面的代码被编译和执行时,它会产生下列结果:

Value of mean : 3.400000


 如果不使用类型转换,结果为 3

 

If you want to get right result you need to write:

#include <iostream>

using namespace std;

int main()
{
  double test = ((double)1 / 2) * 2;
  cout << test << endl;
  return 0;
}

 

 

可以参考:

C++整除:

https://zhidao.baidu.com/question/239931071.html

强制类型转换:

https://www.cnblogs.com/bytebee/p/8535552.html

 stack flow 上:

https://stackoverflow.com/questions/30188016/c-why-does-1-2-2-return-0

 

加油~

 

posted @ 2020-11-07 20:19  千家诗  阅读(1224)  评论(0编辑  收藏  举报