網站首頁 編程語言 正文
計算一個整數的位數
只需要設計一個計時器,因為C語言中除法只留下整數部分,所以可以拿數字/10;數字位數即為循環次數,待n為個位時n/10=0,然后循環結束。
#include<stdio.h>
int main()
{
int n;
int count = 0;
scanf("%d",&n);
if(n == 0)//n為0的情況,個人感覺無位數,退出
{
return 0;
}
else
{
while(n)
{
n=n/10;//每次去掉數字最后一位
count++;//循環一次計數器+1
}
}
printf("%d",count);
return 0;
}
關于如何獲取整數各個位
對于這個在實際的編程題中應用比較多,做了一個總結。
基礎思路
...
int i=123,a;
a = i%10;
printf("a=%d",a);
輸出的便是i的個位數
a=3
然后知道通過 i/10 便可"清除"個位數
由此我們便可以通過循環此方法獲取各個位數
...
int i=123,a,b,c;
a = i%10;
i/=10;
b = i%10;
i/=10;
c = i%10;
i/=10;
printf("a=%d,b=%d,c=%d",a,b,c);
輸出的a,b,c便是 i 的個位數,十位數,百位數
于是我們便知道將整數反轉的方法
...
int i;
long rex = 0;//反轉后的整數
while(i != 0){
? ? rex = rex*10 + i % 10;
? ? i = i / 10;
}//溢出判斷暫時忽略
將整數反轉后那我們又可以得到將整數按位存入數組的方法
int i,j,count=0;
int nums[numsSize];//需要存入的數組
long rex = 0;
while(i != 0){
? ? rex = rex*10 + i % 10;
? ? i = i / 10;
}
...
while(rex != 0)
{
? ? j = rex % 10;//獲取個位數
? ? nums[count] = j;
? ? rex/=10;
? ? count++;
}
反之也可以將字符串轉化為整數,不過本質是一樣的,就不多說了。?
原文鏈接:https://blog.csdn.net/qq_43622870/article/details/102313154
相關推薦
- 2023-01-11 openCV-Python筆記之解讀圖像的讀取、顯示和保存問題_python
- 2022-12-09 Go?Web實戰之創建項目及增加日志功能_Golang
- 2022-07-11 Mongodb分片技術理論
- 2022-07-16 搭建一個Electron跨平臺桌面應用程序
- 2023-03-01 Golang?Makefile示例深入講解使用_Golang
- 2022-12-23 C++類成員函數中的名字查找問題_C 語言
- 2023-10-14 c/c++--編譯指令(預處理之后) #pragma
- 2022-10-11 線上nginx偶爾出現502錯誤
- 最近更新
-
- 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同步修改后的遠程分支