当前位置:网站首页>C语言初级—从键盘接收一个整形并逆序输出
C语言初级—从键盘接收一个整形并逆序输出
2022-08-02 14:03:00 【iccoke】
从键盘接收一个整形并逆序输出
基本思想:从键盘接收一个整形并且逆序输出,大体思路是从键盘输入一个整形,然后获取到这个整形的每一位,最后再将每一位逆序输出
在获取键盘输入的数的每一位之前,首先应该获取键盘输入数的位数
https://blog.csdn.net/iccoke/article/details/125818553?spm=1001.2014.3001.5501
从这可以获取到键盘输入数的位数
具体代码如下
#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<math.h>
int main(){
int num;
scanf("%d", &num);
int count = 0;
while (num != 0);
{
num /= 10;
count++;
}
得到的count即为键盘输入整形的位数
逆序输出的代码如下
#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<math.h>
int main(){
int num;
scanf("%d", &num);
int result = 0;
int count = 0;
int src = num;
while (num != 0);
{
num /= 10;
count++;
}
num = src;
while (count > 0)
{
result += num % 10 * (int)pow(10, count -1);
count--;
num /= 10;
}
printf("%d\n", result);
return 0;
}
我们关注这个代码中的关键几处
int src = num;
num = src;
这两处代码的作用是因为在获取位数和逆序输出的数为同一个数,如果在循环之后直接使用,有可能会出现数据错错误
因此这段代码的作用是记录从键盘接收的整形数并保存,并在逆序输出时使用,防止发生因循环后数据产生错误的情况。
result += num % 10 * (int)pow(10, count -1);
因为pow计算之后默认为double值,而result为int值,无法将一个double值赋给一个int值,这样会发生数据的泄露,因此用(int)对pow计算结果进行强制转换。
同时使用pow等数学函数时,应在头文件加入#include<math.h>。
边栏推荐
- paddleocr window10初体验
- yolov5改进(一) 添加注意力集中机制
- Unit 10 Continuous Tuning
- Raj delivery notes - separation 第08 speak, speaking, reading and writing
- 深度学习框架pytorch快速开发与实战chapter4
- [ROS]ROS常用工具介绍(待续)
- Web Design (Beginners) [easy to understand]
- The IDEA of packaged jar package
- Programming Specifications - LiteOS
- Flask contexts, blueprints and Flask-RESTful
猜你喜欢
What are the file encryption software?Keep your files safe
static关键字3种作用,简单粗暴对比,好理解
[ROS] (01) Create ROS workspace
The 2nd China Rust Developers Conference (RustChinaConf 2021~2022) Online Conference Officially Opens Registration
海明校验码纠错设计原理
IDEA打包jar包
[ROS] (06) ROS Communication - Topic Communication
【c】大学生在校学习c语言常见代码
run yolov5
网络剪枝(1)
随机推荐
verilog学习|《Verilog数字系统设计教程》夏宇闻 第三版思考题答案(第十章)
chapter7
Flask request application context source code analysis
paddle window10环境下使用conda安装
Swagger 的使用
(ROS) (03) CMakeLists. TXT, rounding
drf路由组件Routers
【ROS】编译软件包packages遇到进度缓慢或卡死,使用swap
第三单元 视图层
A little thought about password encryption
Unit 14 Viewsets and Routing
drf view component
Unit 12 associated serialization
c语言用scanf出错不安全的解决办法
verilog学习|《Verilog数字系统设计教程》夏宇闻 第三版思考题答案(第九章)
STM32 (F407) - stack
yolov5 improvement (1) Add attention focus mechanism
[ROS](06)ROS通信 —— 话题(Topic)通信
Deep learning framework pytorch rapid development and actual combat chapter3
Hands-on OCR (1)