C 运行结果每次都不一样?
我初学C, 运行环境是 Mac OS 10.7.4 xcode 4.1刚在做一个课后题,写了以下程序, 运行结果很奇怪,麻烦高手帮忙看一下。谢谢!
这个程序是判断输入的单词里,是不是出现过的letter都正好出现过两次。比如Dada就符合要求。但是我输入horseshoer,返回结果是false。
/* Exercise 8.2*/
#include <stdio.h>
#include <stdlib.h>
int isDoubloon (char letter[])
{
int histogram [26] = {0};
for (int i=0; i<100; i++)
{
letter [i]= tolower (letter [i]);
int index = letter[i] -'a';
histogram [index]++;
}
int count=0;
for (int j=0; j<26; j++)
{
if (histogram [j]==0 || histogram [j]==2)
{
count++;
}
printf("j is %c, count is %i, histogram is %i\n",j+'a', count, histogram [j]); /* This line is for debug */
}
if (count==26)
{
return 1;
}
return 0;
}
int main ()
{
char word [100];
printf("Please enter your word: ");
scanf("%s",word);
if (isDoubloon(word))
{
printf("True\n");
}
else
{
printf("False\n");
}
return 0;
}
输出结果:
Please enter your word: horseshoer
j is a, count is 1, histogram is 0
j is b, count is 2, histogram is 0
j is c, count is 3, histogram is 0
j is d, count is 4, histogram is 0
j is e, count is 5, histogram is 2
j is f, count is 6, histogram is 0
j is g, count is 7, histogram is 0
j is h, count is 8, histogram is 2
j is i, count is 9, histogram is 0
j is j, count is 10, histogram is 0
j is k, count is 11, histogram is 0
j is l, count is 12, histogram is 0
j is m, count is 13, histogram is 0
j is n, count is 14, histogram is 0
j is o, count is 15, histogram is 2
j is p, count is 16, histogram is 0
j is q, count is 17, histogram is 0
j is r, count is 18, histogram is 2
j is s, count is 19, histogram is 2
j is t, count is 20, histogram is 0
j is u, count is 21, histogram is 0
j is v, count is 22, histogram is 0
j is w, count is 22, histogram is 1
j is x, count is 23, histogram is 0
j is y, count is 24, histogram is 0
j is z, count is 25, histogram is 0
False
每次运行结果都不一样,总会有几行的histogram显示是1, 麻烦高手帮忙解答一下,谢谢!
[ 本帖最后由 rixobo 于 2012-9-16 10:24 编辑 ]