2016-01-14 32 views
-4

我试图从int数组中接收最大数字,但它对我来说工作不太好。试图获得最大的数字

for (c = 0; c < 26; c++) 
    { 
     printf("%c occurs %d times in the entered string.\n",c+'a',count[c]); 
     if(count[c] > tempcount1) 
      { 
       temp=count[c]; 
      } 
     tempcount1=count[c]; 
    } 
    printf("%d",temp); 

tempcount1在程序开始时设置为0。有谁知道问题在我的代码中?

+3

你应该比较tempcount1,然后更新温度? – Parttimereaper

+2

当你只需要一个变量时,你似乎有两个单独的变量,'temp'和'tempcount1'。在if语句中删除'temp = count [c];'并移动'tempcount1 = count [c];'然后在最后打印'tempcount1'而不是'temp'。 –

+0

你是不是应该在内部声明'''tempcount1'''而不在其他地方?什么是'''temp'''? –

回答

1

问题是,你在玩杂耍两个变量,它们保持最大数量。与您比较的tempcount1始终会更新,即使当前计数不会更大。

for (c = 0; c < 26; c++) 
    { 
     printf("%c occurs %d times in the entered string.\n",c+'a',count[c]); 
     if(count[c] > tempcount1) 
      { 
       temp=count[c]; 
      } 
     tempcount1=count[c]; 
    } 
    printf("%d",temp); 

以下建议:

int max = 0; 
for (c = 0; c < 26; c++) 
{ 
    printf("'%c' occurs %d times in the entered string.\n", c+'a', count[c]); 
    if(count[c] > max) 
     max = count[c]; 
} 
printf("Max = %d\n", max);