实验环境:
OS: Windows 7
IDE: Visual Studio 2010 Pro
实验代码1:
#include <iostream>
using namespace std;
int main()
{
int a = 1;
int b = 6;
int c = a/b;
cout<< c <<endl;
system( "pause" );
return 0;
}
运行结果:
0
实验代码2:
#include <iostream>
using namespace std;
int main()
{
int a = 1;
int b = 3;
float c = ( float )a/b;
cout<< c <<endl;
system( "pause" );
return 0;
}
运行结果:
0.333333
实验代码3:
#include <iostream>
using namespace std;
int main()
{
int a = 1;
int b = 6;
float c = ( float )a/b;
cout<< c <<endl;
system( "pause" );
return 0;
}
运行结果:
0.166667
实验分析:
类型 | int/int | float/int | float/int | float/int |
被除数 | 1 | 1 | 1 | 1 |
除数 | 2 | 2 | 3 | 6 |
实验值 | 0 | 0.5 | 0.333333 | 0.166667 |
理论值 | 0.5 | 0.5 | 0.333333... | 0.166666... |
结论:
int/int类型的计算值,只保留整数部分,小数部分被舍弃,并且不对运算结果作四舍五入的处理。
float/int类型的计算值,精确到小数点后6位,对运算结果作四舍五入处理。