網站首頁 編程語言 正文
將double/float轉為字符串(帶自定義精度)
char *double_to_string(double d, int decimal) { decimal = decimal < 0 ? 0 : decimal; char *p; char dd[20]; switch (decimal) { case 0: sprintf(dd, "%.0lf", d); break; case 1: sprintf(dd, "%.1lf", d); break; case 2: sprintf(dd, "%.2lf", d); break; case 3: sprintf(dd, "%.3lf", d); break; case 4: sprintf(dd, "%.4lf", d); break; case 5: sprintf(dd, "%.5lf", d); break; default: sprintf(dd, "%.6lf", d); break; } p = malloc(strlen(dd)); strcpy(p,dd); return p; }
需用到頭文件有
#include <stdio.h> #include <stdlib.h> #include <string.h>
簡單用法
double d = 3.1415926; char dstr[20]; sprintf(dstr,"%.2lf",d);//將d 保留2位小數賦值給dstr
float和double精度問題
double和float的區別
是double精度高,有效數字16位,float精度7位。但double消耗內存是float的兩倍,double的運算速度比float慢得多,C語言中數學函數名稱double 和 float不同,不要寫錯,能用單精度時不要用雙精度(以省內存,加快運算速度)。
float和double的精度
是由尾數的位數來決定的。浮點數在內存中是按科學計數法來存儲的,其整數部分始終是一個隱含著的“1”,由于它是不變的,故不能對精度造成影響。
-
float
:2^23 = 8388608,一共七位,這意味著最多能有7位有效數字,但絕對能保證的為6位,也即float的精度為6~7位有效數字; -
double
:2^52 = 4503599627370496,一共16位,同理,double的精度為15~16位。
原文鏈接:https://blog.csdn.net/qq_31028313/article/details/86520864
相關推薦
- 2022-04-07 代碼詳解Python的函數基礎(1)_python
- 2022-11-24 Python模板的使用詳細講解_python
- 2022-04-08 關于Kotlin委托你必須重視的幾個點_Android
- 2022-09-21 Python+pandas編寫命令行腳本操作excel的tips詳情_python
- 2022-06-06 Array.prototype.myfindIndex
- 2022-07-04 Python中字典常用操作的示例詳解_python
- 2022-03-29 python實現矩陣乘法_python
- 2022-10-12 antd為Tree組件標題附加操作按鈕功能_Redis
- 最近更新
-
- window11 系統安裝 yarn
- 超詳細win安裝深度學習環境2025年最新版(
- Linux 中運行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎操作-- 運算符,流程控制 Flo
- 1. Int 和Integer 的區別,Jav
- spring @retryable不生效的一種
- Spring Security之認證信息的處理
- Spring Security之認證過濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權
- redisson分布式鎖中waittime的設
- maven:解決release錯誤:Artif
- restTemplate使用總結
- Spring Security之安全異常處理
- MybatisPlus優雅實現加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務發現-Nac
- Spring Security之基于HttpR
- Redis 底層數據結構-簡單動態字符串(SD
- arthas操作spring被代理目標對象命令
- Spring中的單例模式應用詳解
- 聊聊消息隊列,發送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠程分支