codecamp

C++ 浮点数

学习C++ - C++浮点数

C++浮点类型表示具有小数部分的数字。

它们提供了更大的价值范围。

字面量

C++有两种写入浮点数的方式。

第一个是使用标准的小数点符号:

12.34             // floating-point 
987654.12         // floating-point 
0.12345           // floating-point 
8.0               // still floating-point 

第二种方法称为E符号,它看起来像这样:3.45E6。

这意味着值3.45乘以1,000,000。

E6表示10到6的幂,即1后跟6个零。

因此3.45E6是3,450,000。

6称为指数,3.45称为尾数。

这里有更多的例子:

1.12e+8             // can use E or e, + is optional 
1.12E-4             // exponent can be negative 
7E5                 // same as 7.0E+05 
-12.12e13           // can have + or - sign in front 

例子

下面的代码检查float和double类型。


#include <iostream> 
using namespace std; 
int main() 
{ 
     cout.setf(ios_base::fixed, ios_base::floatfield); // fixed-point 
     float tub = 10.0 / 3.0;     // good to about 6 places 
     double mint = 10.0 / 3.0;   // good to about 15 places 
     const float million = 1.0e6; 

     cout << "tub = " << tub; 
     cout << ", a million tubs = " << million * tub; 
     cout << 10 * million * tub << endl; 

     cout << "mint = " << mint << " and a million mints = "; 
     cout << million * mint << endl; 
     return 0; 
} 

上面的代码生成以下结果。


浮点常量

默认情况下,8.24和2.4E8的浮点常量是double类型。

如果创建一个常量为float类型,则使用f或F后缀。

对于long double类型,您可以使用l或L后缀。

以下是一些示例:

1.234f         // a float constant 
2.45E20F       // a float constant 
2.345324E28    // a double constant 
2.2L           // a long double constant 
C++ 布尔类型
C++ 数组
温馨提示
下载编程狮App,免费阅读超1000+编程语言教程
取消
确定
目录

关闭

MIP.setData({ 'pageTheme' : getCookie('pageTheme') || {'day':true, 'night':false}, 'pageFontSize' : getCookie('pageFontSize') || 20 }); MIP.watch('pageTheme', function(newValue){ setCookie('pageTheme', JSON.stringify(newValue)) }); MIP.watch('pageFontSize', function(newValue){ setCookie('pageFontSize', newValue) }); function setCookie(name, value){ var days = 1; var exp = new Date(); exp.setTime(exp.getTime() + days*24*60*60*1000); document.cookie = name + '=' + value + ';expires=' + exp.toUTCString(); } function getCookie(name){ var reg = new RegExp('(^| )' + name + '=([^;]*)(;|$)'); return document.cookie.match(reg) ? JSON.parse(document.cookie.match(reg)[2]) : null; }