C语言改错题,题目是:输入一串字符,并在字符串中从第m个字符开始截取n个字符#include <stdio.h>#include <string.h>void main(){char str[100],sub[100];int m,n,len,i;printf("Enter string:");gets(str);printf("\nEnter m n:");scanf("%d%d",&m,&n);len=strlen(str);if( m-1+n>len )printf("Can't run with %d and %d!\n",m,n);else{ i=0;/**/ while(i<=n) /**/ i<n{/**/ sub[i]=str[m+i]; /**/ sub[i]=str[m+i-1];i++;}/**/ sub[i]='\n'; /**/ sub[i]='\0'printf("sub string is:%s\n",sub);}getch();}请问中间改错那些为什么是那样子,怎么解释:输入一串字符,并在字符串中从第m个字符开始截取n个字符求程序整个过程解析
2 回答
Eric_温水之蛙
TA贡献8条经验 获得超3个赞
str[0] = 1 str[1] = 2 str[2] = 3 str[3] = 4 str[4] = 5 str[5] = 6 str[6] = 7 str[7] = 8 str[8] = 9 m=3,n=4 循环1: i = 0 判断i<n => 0<4 -> true sub[i]=str[m+i-1] =>sub[0]=str[3+0-1] -> sub[0] = 3 i++ -> i=1 循环2: i = 1 判断i<n => 1<4 -> true sub[i]=str[m+i-1] =>sub[1]=str[3+1-1] -> sub[1] = 4 i++ -> i=2 循环3 i = 2 判断i<n => 2<4 -> true sub[i]=str[m+i-1] =>sub[2]=str[3+2-1] -> sub[2] = 5 i++ -> i=3 循环4: i = 3 判断i<n => 3<4 -> true sub[i]=str[m+i-1] =>sub[3]=str[3+3-1] -> sub[0] = 6 i++ -> i=4 循环5: i = 4 判断i<n => 4 < 4 -> false 跳出while sub[i] = '\0 => 'sub[4] ='\0' 此时sub的值为 sub[0] ='3' sub[1] ='4' sub[2] ='5' sub[3] ='6' sub[4] ='\0'
- 2 回答
- 0 关注
- 1836 浏览
添加回答
举报
0/150
提交
取消