私信TA

用户名:chenqi

访问量:33878

签 名:

等  级
排  名 356
经  验 5107
参赛次数 0
文章发表 52
年  龄 0
在职情况 学生
学  校
专  业

  自我简介:

TA的其他文章

//此代码在visual studio上运行没问题,为什么在此平台上运行报错
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main()
{
	int i = 0,num,sum = 0;
	while(scanf("%d",&num)!=EOF)
	{
		for(i=0;num > 0;i++)
		{
			sum += num%10;
			num -= num%10;
			num = num / 10;	
		}
		printf("%d\n",sum);
		sum = 0;
	}
	system("pause");
}
错误分析:
    注意题目要求“求输入数(<2^32)的Tom数”,即将输入num定义为整型类型不能保证所有的输入数据都能够被正确读入。

正确执行:
方案1:
#include <stdio.h>
int main()
{
   long long int i = 0,num,sum = 0;
    while(scanf("%lld",&num)!=EOF)
    {
        for(i=0;num > 0;i++)
        {
            sum += num%10;
            num -= num%10;
            num = num / 10;
        }
        printf("%lld\n",sum);
        sum = 0;
    }
}

方案2:
#include <stdio.h>
#include <string.h> 
int main()
{
    int i=0,num,sum=0,length = 0;
    char s[1000];

    while(scanf("%s",&s)!=EOF)    //注意读入字符串后程序自动添加‘\0’
	{
	    length = strlen(s);    //若字符串最后没有‘\0’,此句将返回不确定值
            for(i=0;i<length;i++)
            {
                sum += (s[i]-'0');
            }

        printf("%d\n",sum);
        sum = 0;
    }
}


 

0.0分

0 人评分

看不懂代码?想转换其他语言的代码? 或者想问其他问题? 试试问问AI编程助手,随时响应你的问题:

编程语言转换

万能编程问答

代码解释器

  评论区

提交啥错?
2017-10-20 10:07:19
  • «
  • 1
  • »