找错误——下面的程序意图在于统计字符串中字符数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个问题,一个导致程序无法运行,另一个导致结果不正确,还有一个导致效率低下。你能找到并改正他们吗?

关于此题我只找到了3处错误

(1)缺少#include<string.h>

(2)#define maxn 10000000+10,太大,不能作为数组的大小定义。

(3)if (s[i]==1)tot++;应该为if (s[i]==‘1’)tot++;

此为《算法竞赛入门经典》P55的题目

时间: 2024-07-30 17:07:52

找错误——下面的程序意图在于统计字符串中字符数1的个数,可惜有瑕疵的相关文章

技巧之C#统计字符串中字符出现的次数(转)

方法1.自定义类 class CharNum { private char c; private int num; public char C { get { return c; } } public int Num { get { return num; } set { num = value; } } public CharNum(char ch) { this.c = ch; this.num = 1; } } static void Main(string[] args) { /* */

java统计字符串中字符及子字符串个数

import java.util.Scanner;public class Counter { static Scanner scanner = new Scanner(System.in); public static void count(String s) { int low, upper, num, others; low = upper = num = others = 0; for (int i = 0; i < s.length(); i++) { if (Character.is

【c++程序】统计字符串中字符出现次数

#include<iostream> #include<string> //#include<cstring> using namespace std; int main() { string str; cout<<"input some text:"<<endl; getline(cin,str); //char str[200]; //cin.getline(str,200); int cnt[256]={}; for(i

c 统计字符串中字符出现的个数

1.单纯用数组来解题 思路:从左往右循环,每次碰到一个字符就和左边的字符串比较,如果有相同的就右移,如果没有找到相同的就从这个位置向右统计个数并输出. 1 #include<stdio.h> 2 3 void calCount(char arr[]) 4 { 5 int i,j,count,had; 6 i = j = count = had = 0; 7 while(arr[i] != '\0') 8 { 9 count = 0; 10 had = 0; 11 for(j=0; j<i

统计字符串中的删除的单词个数

public class Demo24 { public static void main(String[] args) { String s = "woaijavahahajavaaiwo"; //原来字符串的长度 int length = s.length(); //删除后的长度 int replace = s.replace("java", "").length(); //删除的总长度 int x =length-replace; //单个

R语言统计字符串的字符数ncahr函数

函数计算字符数量,包括在一个字符串的空格的个数. 语法 nchar()函数的基本语法是: nchar(x) 以下是所使用的参数的说明: x - 向量输入. 示例 result <- nchar("Count the number of characters") print(result) 当我们上面的代码执行时,它产生以下结果: [1] 30

统计字符串中字符出现的次数

var a = {}; var str = 'gouod'.split(""); str.forEach(function (v, i) { a[v] = a[v] == undefined ? 1 : a[v] + 1; }) console.info(a)

统计字符串中字符出现的次数(||和&amp;&amp;的区别)

var str = "ProsperLee"; // || 返回第一个为真的表达式的值,若全为假则返回最后一个表达式的值 // && 返回第一个为假的表达式的值,若全为真则返回最后一个表达式的值 String.prototype.charCount = function(){ var json = {}; for (var i = 0, l = this.length; i < l; i++) { json[this[i]] = json[this[i]] + 1

python统计字符串中每个单词出现的个数【一行】

s = 'i am very very like you and like you' dict( [(i, s.split().count(i)) for i in s.split()] ) Out[2]: {'i': 1, 'am': 1, 'very': 2, 'like': 2, 'you': 2, 'and': 1} set( map(lambda x:(x, s.split().count(x)), s.split()) ) Out[6]: {('am', 1), ('and', 1)