2012-01-05 43 views
-4

下面的代碼應計算按下的按鍵數量並將其與按下的數字鍵的百分比一起打印在屏幕上。當我運行代碼時,百分比總是爲0.爲什麼?未能計算鍵擊的百分比是數字

#include <stdio.h> 
#include <stdlib.h> 
#include <conio.h> 


int main() 
{ 
int c,count=0,count1=0; 
float d; 
while ((c=getch())) 
{ 
    count = count++; 
if (c=='1'||c=='2'||c=='3'||c=='4'||c=='5'||c=='6'||c=='7'||c=='8'||c=='9'||c=='0') 
    { 
     count1=count1++; 
    } 
    if (c=='!') 
    { 
     d=(count1/count*100); 
     printf("\nnumbers of keys is %d percentage of number keys is %.3d percent",count,d); 
    } 

    } 
return 0; 

}

+5

提問。你做錯了。 – log0 2012-01-05 20:11:11

+4

遞增,你也做錯了。 – 2012-01-05 20:13:20

+2

對上面的註釋和下面的註釋+1都+1。 1)不要使用全部大寫,2)不要使用未定義的行爲('x = x ++'==未定義的行爲,查找順序點)。 3)整數除法失敗。 – Joe 2012-01-05 20:16:03

回答

0

的問題是,即使d是float,countcount1int。因此,你在做整數運算時,你說

d=(count1/count*100); 

而是執行此操作:

d=((float)count1/count*100); 

鑄造count1floatconverts the division to floating point

2

線條

count = count++; 

count1 = count1++; 

是不確定的行爲,因此,所有的賭注都關閉。即使它不是未定義的行爲,它也不會做你想做的事情,因爲x++在增量之前返回值x

讓我們簡單地說是++count;++count1;

+0

好的。 'count ++;'和'count1 ++;'也可以。 – Caleb 2012-01-05 20:23:54