|
发表于 2019-1-31 10:09:49
|
显示全部楼层
本帖最后由 行客 于 2019-1-31 10:10 编辑
请观察注释:
- // test.cpp : Defines the entry point for the console application.
- //
- #include "stdafx.h"
- #include <stdio.h>
- int main()
- {
- int ch;
- int num = 0; // num为整型变量,初始化为0。在do循环里是将输入的字符转变为数字,并组成整型变量。
- printf("请输入待转换的字符串:");
- do
- {
- ch = getchar();
- if (ch >= '0' && ch <= '9')
- {
- num = 10 * num + (ch - '0'); // 假设你输入的是字符串为'67a'。
- // 第一次循环,ch为'6':num = 10 * 0 + (54 - 48),num值为6。ch即6的ASII码为54,'0'的ASII码为48
- // 第二次循环,ch为'7':num = 10 * 6 + (55 - 48),num值为67。
- // 第三次循环:ch 为'a',进入下面的else。
- }
- else
- {
- if (num)
- {
- break;
- }
- }
- }
- while (ch != '\n');
- printf("结果是:%d\n", num);
- return 0;
- }
复制代码 |
|