2017-04-15 12 views
0

コードは、1からxまでの数値の合計を見つけるか、 xの階乗xの値を入力すると、ifおよびelse if文を実行せずにプログラムは直接終了します。これは私のコードです。ユーザに数字nを求めて、合計の計算とnの階乗の計算のどちらかを選択するプログラムを提供するプログラム

#include <stdio.h> 

int sum(int num); 
int fact(int num); 

int main(void) 
{ 
    int x = 0; 
    char choice; 
    printf("Enter a number : \n"); 
    scanf("%d", &x); 
    printf("Enter f for factorial, s for sum \n"); 
    choice = getchar(); 

    //These lines are ignored by C 
    if (choice == 'f' || choice == 'F') 
    { 
     printf("The factorial of %i is %i \n",x, fact(x)); 
    } 
    else if (choice == 's' || choice == 'S') 
    { 
     printf("The sum from 1 to %i is %i \n",x, sum(x)); 
    } 
} 

int sum (int num) 
{ 
    int sum =0; 
    for (int i =1; i <=num; i++) 
     sum = sum+i; 
     return sum;  
} 

int fact (int num) 
{ 
    int fact =1; 
    for (int i =1; i <=num; i++) 
     fact = fact*i; 
     return fact;  
} 

誰でも私のコードに間違いがありますが、どうすれば修正できますか?ありがとうございました。

+0

可能な重複[なぜ(のgetcharはありません)私はscanfの後にEnterキーを押すのを待つ()?](HTTP:/

これを避けるために、あなたのコードの変更を以下のようにしよう/image/gif/paws/1391548/why-doesnt-getchar-wait-for-me-to-press-enter-after-scanf) – rsp

答えて

1

バッファの問題だと思います。だから、

scanf(" %d", &x); 
     ^^^ 
    white-space 

代わりに

scanf("%d", &x); 

また、このコードGETCHARである()関数で

scanf(" %c", &choice); 

代わりに

choice = getchar(); 
+0

'%d'の前に空白を入れる必要はありません。 –

0

問題を使用を使用し。

最初のスキャン時:scanf("%d", &x);ユーザがEnterキーを押すと、入力バッファに残り、整数valは変数xに格納されます。

2回目のスキャン時:choice = getchar();、可変キーで入力キーを読み取ります。 そして、あなたが書かれている2つのだけ条件:

  1. if (choice == 'f' || choice == 'F')
  2. それは直接コードを終了している理由だ
  3. else if (choice == 's' || choice == 'S')

。あなたはこのような「他の」部分を記述する場合は「F」と「s」は

以外の選択肢=のために書かれたコードがないよう:

else printf("%d", choice); 

それが印刷されます:10のASCII値でありますEnter/New改行。

int x = 0; 
char choice; 
printf("Enter a number : \n"); 
scanf("%d", &x);  //here the integer is scanned in variable 'x' 
choice = getchar();  //here the enter key is scanned in variable 'choice' so now input buffer is free 
printf("Entr f for factorial, s for sum \n"); 
scanf("%c", &choice); //here the character entered by use will be stored in variable 'choice' so it is overwritten. 
関連する問題