数据类型范围问题
对于以下两个程序:为何前者在测试到m=10000000000时可以正常输出x的值,而第二个程序当测试到m=10000000000时却不能正常输出x的值?
C语言版:
#include<stdio.h>
main() {
float m;int a;
scanf("%d",&a);
while(a--) {
scanf("%f",&m);
printf("%.0f\n",(m-1)*1000+471);}
}
C++版:
#include<iostream>
using namespace std;
main()
{
int a;cin>>a;
double x,m;
while(a--){
cin>>m; x = (m-1)*1000 + 471 ;
cout<<x<<endl;}
}
[解决办法]
跟cout的默认输出格式有关系
试下这个
- C/C++ code
……#include<iostream>#include <iomanip>using namespace std;main(){ int a;cin>>a; double x,m; while(a--){ cin>>m; x = (m-1)*1000 + 471 ; cout<<fixed<<x<<endl; }}
[解决办法]
看lz的c代码是想把小数部分去掉了:
- C/C++ code
cout<<fixed<<setprecision(0)<<x<<endl;
[解决办法]
参考float.h:
- C/C++ code
...#define DBL_DIG 15 /* # of decimal digits of precision */#define DBL_EPSILON 2.2204460492503131e-016 /* smallest such that 1.0+DBL_EPSILON != 1.0 */#define DBL_MANT_DIG 53 /* # of bits in mantissa */#define DBL_MAX 1.7976931348623158e+308 /* max value */#define DBL_MAX_10_EXP 308 /* max decimal exponent */#define DBL_MAX_EXP 1024 /* max binary exponent */#define DBL_MIN 2.2250738585072014e-308 /* min positive value */#define DBL_MIN_10_EXP (-307) /* min decimal exponent */#define DBL_MIN_EXP (-1021) /* min binary exponent */#define _DBL_RADIX 2 /* exponent radix */#define _DBL_ROUNDS 1 /* addition rounding: near */#define FLT_DIG 6 /* # of decimal digits of precision */#define FLT_EPSILON 1.192092896e-07F /* smallest such that 1.0+FLT_EPSILON != 1.0 */#define FLT_GUARD 0#define FLT_MANT_DIG 24 /* # of bits in mantissa */#define FLT_MAX 3.402823466e+38F /* max value */#define FLT_MAX_10_EXP 38 /* max decimal exponent */#define FLT_MAX_EXP 128 /* max binary exponent */#define FLT_MIN 1.175494351e-38F /* min positive value */#define FLT_MIN_10_EXP (-37) /* min decimal exponent */#define FLT_MIN_EXP (-125) /* min binary exponent */#define FLT_NORMALIZE 0#define FLT_RADIX 2 /* exponent radix */#define FLT_ROUNDS 1 /* addition rounding: near */...