《算法竞赛入门经典》第三章思考题
题目2(统计字符1的个数):下面的程序意图在于统计字符串中字符1的个数,可惜有
瑕疵:
#include<stdio.h>
#define maxn 10000000 + 10
int main() {
char s[maxn];
scanf("%s", s);
int tot = 0;
for(int i = 0; i < strlen(s); i++)
if(s[i] == 1) tot++;
printf("%d\n", tot);
}
该程序至少有3个问题,其中一个导致程序无法运行,另一个导致结果不正确,还有一
个导致效率低下。你能找到它们并改正吗?
答案:
#include<stdio.h>
#include<string.h>
#define maxn 10000000 + 10
char s[maxn];
int main(){
scanf("%s", s);
int tot = 0;
for(int i = 0; i < strlen(s); i++)
if(s[i]-'0' == 1) tot++;
printf("%d\n", tot);
}
错误共有三处:
1.缺少头文件#include<string.h>
2.maxn的数量太大,则只能在函数外进行定义
3.输入的数据为字符串,要与数字1进行比较,则应该-'0’将字符变为int类型