2017-01-26 16 views
0

whileループ内のif文を使用して、この単純なCプログラムで間違った値を入力するのを防止しようとしています。しかし、問題は、ユーザーが間違った値を入力するたびに変数に格納され、同じ値がその後の計算に使用されることです。 実際のプログラムは次のとおりです。ユーザーが入力した間違った値が変数に格納されないようにするには?

#include <stdio.h> 
#include <stdlib.h> 
/*Program to calculate the marks obtained scored by the class in a quiz*/ 

    int main() 
    { 
    float marks, average, total = 0.0; 
    int noStudents; 
    printf("Enter the total number of students: "); 
    scanf("%d", &noStudents); 
    int a=1; 
    while(a<=noStudents) 
    { 
     printf("Enter marks obtained out of 20: "); 
     scanf("%f", &marks); 
     if(marks<0 || marks >20) 
     { 
      printf("You have entered wrong marks\nEnter again: "); 
      scanf("%d", &marks); 
     } 
     total = total+marks; 
     a++; 
    } 
    average = total/(float)noStudents; 
    printf("Average marks obtained by the class are: %f", average); 


    return 0; 
} 
+5

あなたもチェックし、 'のscanf()'からの復帰を扱う、または以外の場合は、問題があるでしょうべきで続い*他*変数にそれを読んで、それを最初に確認してください... –

+0

数字(または空白)が入力されます。 – Dmitri

答えて

2

最初の問題は、コードの不一致です。条件文の本体内に、あなたは%dのための不一致引数の型を使用しています

scanf("%d", &marks); 

を書きました。これによりundefined behaviorが呼び出されます。これまで通り%fを使用してください。それをしないと述べた

、あなたがにユーザーに頼っている

  • は、自ら第二の試みで修正します。ループを使用して、有効な値を取得した後にのみ、それを打ち切ってください。
  • average = total/(float)noStudents;というステートメントでは、キャストは必要ありません。オペランドの1つ、totalはすでにfloatタイプです。したがって、明示的キャストがない場合でも、他のオペランドは自動的に昇格され、浮動小数点除算が行われます。
0

コードを少し微調整しました。それが役に立てば幸い。コメントの1つで既に述べたように、ユーザーが範囲外のシナリオで正しい値を与えることを期待しないでください。正しい値を入力しない限り、範囲内で入力するようユーザーに依頼してください。

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

int main() 
{ 
    float marks, average, total = 0.0; 
    int noStudents; 
    printf("Enter the total number of students: "); 
    scanf("%d", &noStudents); 
    int a=1; 

    while(a<=noStudents) 
    { 
     printf("Enter marks obtained out of 20: "); 
     scanf("%f", &marks); 
     if(marks<0 || marks >20) 
     { 
      printf("You have entered wrong marks.Enter again:\n "); 
      continue; 
     } 
     total = total+marks; 
     a++; 
    } 
    average = total/noStudents; 
    printf("Average marks obtained by the class are: %f", average); 

    return 0; 
} 
関連する問題