2013-06-26 106 views
-1

編寫一個程序,該程序根據用戶的請求顯示整數0至9的新隨機排列。例如,該程序的輸出可能如下:如何在此代碼中增加

當用戶輸入no時,程序應打印多少個7被打印。

我的代碼:

#include <stdio.h> 
#include <stdlib.h> 
#include <string.h> 
#include <ctype.h> 

int main() 
{ 
    int i , total , r; 
    char ans; 
    srand(time(NULL)); 
    do{ 
     for(i=0 ; i < 10 ; i++) 
     { 
      r= (rand()%(9-1+1)) + 1; 
      printf ("%d ",r); 
     } 
     total =0; 
     if (r==7) // Here how can I correct this so total will increase every time 
     {   // there is a 7 in the string 
      total++; 
     } 
     printf("\nAnother permutation: y/n?\n"); 
     scanf(" %c",&ans); 
     if (ans != 'y') 
     { 
      printf("Bye!\n"); 
      printf("The number of 7's is: %d", total); 
     } 
    }while(ans=='y'); 
    return 1; 
} 

我有我的代碼有問題。如何在!='y'後增加此程序中顯示的7。

+1

請格式化您的代碼。 – Elazar

+1

並告訴我們你的問題是什麼。 – 2013-06-26 07:23:46

+0

(哦,我知道了。通常的'scanf(「%c」)' - extranewline - whynotterminating「問題...) – 2013-06-26 07:24:29

回答

1

設置total=0在進入do-while循環之前,得到正確的total

+0

也擴展for循環包含'if(r == 7)'語句(我的解法假設你想計算在所有生成的隨機數中出現的7的總數) – amulous

+0

謝謝,for循環的擴展工作。 –