2016-12-05 11 views
-2

ここに私のコードです。その学校の割り当て。私はバビロニア人が開発した方法を使って数の平方根を計算するプログラムを作らなければなりませんでしたが、それは重要な部分ではありません。私がscanfの文字を無視することができれば、私が手紙を入力すると、それは私の端末に凶暴になることがないように私が思っていたことです。どんな助けでも大歓迎です。"scanf_s"の特定の文字を無視することはできますか?

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

double root_Approach(double s); // defines the two functions 
void ask_Number(void); 

int main() { 

    ask_Number(); // calls function ask_Number 

    printf("\n\n"); 
    system("pause"); 
    return 0; 
} 

double root_Approach(double s) { 

    double approach; 
    approach = s; 
    printf("%.2lf\n", s);  // prints initial value of the number 

    while (approach != sqrt(s)) {   // keeps doing iteration of this algorithm until the root is deterimened 

     approach = (approach + (s/approach)) * 0.5; 

     printf("%lf\n", approach); 
    } 

    printf("The squareroot of %.2lf is %.2lf\n",s, sqrt(s)); // prints the root using the sqrt command, for double checking purposes 

    return approach; 
} 

void ask_Number(void) { 

    double number; 

    while (1) { 
     printf("Input a number greater than or equal to 0: "); // asks for a number 
     scanf_s("%lf", &number); // scans a number 

     if (number < 0) { 
      printf("That number was less than 0!!!!!!\n"); 
     } 
     else { 
      break; 
     } 
    } 
    root_Approach(number); 
} 
+0

役立つかもしれない "それだけで、再び同じ質問を"。 'scanf'は決して再試行しません。あなたはそれを自分で行う必要があります。実際、 'scanf'は無効な入力を処理するのには間違いがあります(無効な入力を消費しません)。代わりに、 'fgets'と' sscanf'を使って提案してください。 – kaylum

+1

'scanf_s'の戻り値を確認してください。ゼロの場合、エラーメッセージを出力し(オプション)、 'int c;を使用して入力ストリームをフラッシュします。 while((c = getchar())!= '\ n' && c!= EOF); '。 http://stackoverflow.com/a/4016721/3049655を参照してください。 –

答えて

2
  1. Scanfあなたができる一つの方法は、読み取り入力が整数であるかどうかscanfのreturn文をチェックすることです

ターミナル(文字または整数)から入力することができるものは何でも読み整数ではありません。ここで

は、サンプルコードは

int num; 
    char term; 
    if(scanf("%d%c", &num, &term) != 2 || term != '\n') 
     printf("failure\n"); 
    else 
     printf("valid integer followed by enter key\n"); 

`

あるこのリンクは Check if a value from scanf is a number?

関連する問題