c语言程序为何有一半不运行
答案:2 悬赏:0
解决时间 2021-03-12 03:59
- 提问者网友:放荡不羁
- 2021-03-11 18:58
//给一个不多于5位的正整数,
#include
#include
int main()
{
int num,indiv,ten,hundred,thousand,ten_thousand,place;
printf("请输入一个整数(0~99999):");
scanf("%d",&num);
if(num>9999)
place=5;
else if(num>999)
place=4;
else if(num>99)
place=3;
else if(num>9)
place=2;
else place=1;
printf("位数:%d\n",place);
printf("每位数字为:");
ten_thousand=num/10000;
thousand=(int)(num-ten_thousand*10000)/1000;
hundred=(int)(num-ten_thousand*10000-thousand*1000)/100;
ten=(int)(num-ten_thousand*10000-thousand*1000-hundred*100)/10;
indiv=(int)(num-ten_thousand*10000-thousand*1000-hundred*100-ten*10);
switch(place)
{case5:printf("%d,%d,%d,%d,%d",ten_thousand,thousand,hundred,ten,indiv);
printf("\n反序数字为:");
printf("%d,%d,%d,%d,%d\n",indiv,ten,hundred,thousand,ten_thousand);
break;
case4:printf("%d,%d,%d,%d",thousand,hundred,ten,indiv);
printf("\n反序数字为:");
printf("%d,%d,%d,%d\n",indiv,ten,hundred,thousand);
break;
case3:printf("%d,%d,%d",hundred,ten,indiv);
printf("\n反序数字为:");
printf("%d,%d,%d\n",indiv,ten,hundred);
break;
case2:printf("%d,%d",ten,indiv);
printf("\n反序数字为:");
printf("%d,%d\n",indiv,ten);
break;
case1:printf("%d",indiv);
printf("\n反序数字为:");
printf("%d\n",indiv);
break;
}
return 0;
}
最佳答案
- 二级知识专家网友:24K纯糖
- 2021-03-11 20:26
你的数据格式输入输出有错误。
case5 应该是case 空格 5 ;你丢失了空格所以错误了。
全部回答
- 1楼网友:旧事诱惑
- 2021-03-11 22:03
有点儿意思。原因却出乎意料的简单。 char *rwtab[27]={"main","if","then","while","do"," static","int"," double","struct","break","else","long","switch","case","typedef","char","return","const","float","short","continue","for","void","sizeof","default","do"}; 少了一项,只有26项,rwtab[26]是空指针,访问到它时,就出错了。错误提示如下: 我没有修改这一句的时候,在你指出出错的地方加了下面一句: for(n=0;n<27;n++) if(strcmp(token,rwtab[n])==0)//比较是否关键字 { printf("cathch a key-word\n"); // } 出错了,提示信息如下: 这意味着,访问了一个空指针。 修改如下: char *rwtab[27]={"main","if","then","while","do","static","int",\"double","struct","break","else","long","switch","case",\"typedef","char","return","const","float","short","continue",\"for","void","sizeof","default","do","long"};//数组少一项,没有27项,另外几个关键词前面有空格,也应该删除。 加了续行符号。修改之后,运行成功: 我用你的程序做a.txt,生成文件b.txt,c.txt,今天不知什么情况,不能上传。 为什么这样?很玄妙: rwtab数组少一项,rwtab[26]会引用一个空指针,产生错误。这儿没有语句时,循环没有实质性语句,编译程序优化, 不会编译这个循环的语句,程序中根本没有这几句的内容,因而不会出错。有了语句,就不能省略了,就出错了。 就是这样简单。 另外,你的程序必须当做c++程序编译,否则通不过。c不允许在有实质语句之后定义变量,变量说明要全部放到相应段的最前面,也不支持//注释。我是用devc++编译成功的,用wintc编译失败。
我要举报
大家都在看
推荐资讯