13课课后作业
#include <stdio.h>int main()
{
int ch;
int num = 0;
printf("请输入待转换的字符串:");
do
{
ch = getchar();
if (ch >= '0' && ch <= '9')
{
num = 10 * num + (ch - '0');//看不懂
}
else
{
if (num)
{
break; // 如果已有数字,则退出循环
}
}
}
while (ch != '\n');
printf("结果是:%d\n", num);
return 0;
}
请问第十六行是什么意思,谢谢
主要问题:
1. `getchar()` 函数只能读取一个字符,如果需要输入多个字符组成字符串,可以使用 `gets()` 函数或者 `fgets()` 函数。
2. 缺少处理换行符的代码。
修改后的代码如下:
#include <stdio.h>
int main()
{
char str;
int num = 0;
printf("请输入待转换的字符串:");
gets(str);
for (int i = 0; str != '\0'; i++) {
if (str >= '0' && str <= '9') { // 判断字符是否是数字
num = num * 10 + (str - '0'); // 将字符转换成数字
}
}
printf("转换后的数字为:%d\n", num);
return 0;
}
修改说明:
1. 将 `ch` 改为字符数组 `str`,并增加一个大小为 100 的数组来存储待转换的字符串。
2. 使用 `gets()` 函数来读取字符串。
3. 使用循环遍历字符串,判断每个字符是否为数字,并将其转换为数值。
4. 输出转换后的数字。
以上回复来自 FishC AI 小助理,如未能正确解答您的问题,请继续追问。 #include <stdio.h>
int main(void)
{
char c , s[] = {'1' , '3' , '5' , '4' , '2' , '0' , '\0'} ;
int n ;
n = 0 ;
c = s - '0' ; c = '1' - '0' = 1
n = n * 10 + c ; n = 0 * 10 + 1 = 1
c = s - '0' ; c = '3' - '0' = 3
n = n * 10 + c ; n = 1 * 10 + 3 = 13
c = s - '0' ; c = '5' - '0' = 5
n = n * 10 + c ; n = 13 * 10 + 5 = 135
c = s - '0' ; c = '4' - '0' = 4
n = n * 10 + c ; n = 135 * 10 + 4 = 1354
c = s - '0' ; c = '2' - '0' = 2
n = n * 10 + c ; n = 1354 * 10 + 2 = 13542
c = s - '0' ; c = '0' - '0' = 0
n = n * 10 + c ; n = 13542 * 10 + 0 = 135420
printf("%d\n" , n) ;
}
页:
[1]