当前位置:网站首页>C语言入门实战(11):输入一组正整数,求逆序数的和
C语言入门实战(11):输入一组正整数,求逆序数的和
2022-07-23 09:00:00 【liberg】
这是《C语言入门实战》系列的第11篇。
上一篇:C语言入门实战(10):取模问题
题目
对键盘输入的任意一组正整数(个数任意),求所有数的逆序数之和,这里的逆序数是指对该数从右向左顺序读得到的数,例如123的逆序数是321,1200的逆序数是21。输入非数字时结束程序。请编程解决该问题。
要求
输入输出格式示例1:
输入:170<回车>
x<回车>
输出:71
输入输出格式示例2:
输入:21<回车>
130<回车>
89<回车>
125<回车>
90<回车>
a<回车>
输出:671
参考代码
#include <stdio.h>
#include <stdlib.h>
// 定义一个函数,计算输入整数n的逆序数
int reverseNum(int n) {
int a = 0;
while(n>0) {
a = a*10 + n%10;
n /= 10;//即n=n/10
}
return a;
}
int main(int argc, char *argv[]) {
int result = 0;
int n;
char ch;
int flag = 1;
while(flag) {
n = 0;
ch = getchar();
while(ch!='\n' && ch!=EOF) {
if (ch>='0' && ch <='9') {
n = n*10 + ch-'0';
} else {
//读取到非正整数的字符,设置退出标记
flag = 0;
break;
}
ch = getchar();
}
//对应输入的组内合法的正整数值,得到其逆序数,累加进答案中
result += reverseNum(n);
}
printf("%d", result);
return 0;
}
代码复盘
我们定义了一个函数(函数用于封装可复用的代码单元),int reverseNum(int n),根据输入的整型值n计算返回n的逆序数。
&&是逻辑and符号,是“并且”的意思。
getchar()在标准库头文件stdio.h中声明,用于从标准输入(一般是键盘)读取一个字符。
EOF是stdio.h中定义的常量(常量值为-1),表示读到了文件/标准输入末尾。因为正常来讲,从文件或标准输入读取一个字节,这个字节一定是>=0的字符,所以可以规定-1常量表达读取结束了。
边栏推荐
猜你喜欢

ValidationError: Invalid options object. Dev Server has been initialized using an options object th

手工测试如何转向自动化测试?字节5年自动化经验浅谈一下...

初识并查集

js日历样式饼图统计插件

【WinForm】关于截图识别数字并计算的桌面程序实现方案

4. Find the median of two positive arrays

Optimisation du serveur Cloud Huawei avec connexion clé

Canvas 从入门到劝朋友放弃(图解版)

【模电复习——二极管】

Cool code rain dynamic background registration page
随机推荐
Experience in developing large crawlers in requests Library
(重链剖分)魔法树
[download attached] several scripts commonly used in penetration testing that are worth collecting
优化华为云服务器采用Key登陆
How can manual testing turn to automated testing? Byte 5 years of automation experience talk about
webstrom ERROR in [eslint] ESLint is not a constructor
【PyQt5安装以及使用】
Pagehepler lost the pit of the original SQL order by condition
解决使用bert encoder出现的一系列问题
FPGA工程师如何进行复杂系统设计?
js纹理样式饼图插件
初识并查集
Tensor, numpy, PIL format conversion and image display
可以进行2D或3D三角剖分的一些库
扁平样式反馈表单页面
Is it risky and safe to open a mobile stock account?
基金开户网上办理是否安全?谁给解答一下
右键新建txt,新建文本文件不见了,通过添加注册表就可以解决,找来找去办法解决不了的终极办法
视觉与智能学习近期期刊阅读与相关知识学习
固定资产管理系统哪家好?固定资产管理平台有哪些?