下面的程序意图在于统计字符串中字符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);
return 0;
}
该程序至少有3个问题,其中一个导致程序无法运行,另一个导致结果不正确,还有一个导致效率低下。你能找到它们并改正吗?
错误:
1.数组设置过大,应将数组声明在外面;
2.如果数组长度过大,那么strlen()计算长度的时间就会加长,况且每进行一次for循环,都要计算,会浪费不必要的时间
3.s[i]==‘1’ 此处一定要注意,字符数组应该和字符相匹配,否则出错;
#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;s[i];i++)//这一种遍历方法比较有技巧,需要理解
if(s[i]=='1')tot++;
printf("%d\n",tot);
}
或者
#include<stdio.h>
#include<string.h>
#define maxn 10000000+10
char s[maxn];
int main()
{
scanf("%s",s);
int tot=0;
int length=strlen[s];
for(int i=0;i<length;i++)//相比之下,上一种方法要比这一种好一些,但是这个是最容易想到的;
if(s[i]=='1')tot++;
printf("%d\n",tot);
}