私はこの単純なプログラムを書いています。これはユーザーが入力した数値の階乗を計算することになっています。プログラムは、新しい番号の階乗を見つけるために、プログラムを停止または続行するようユーザーに尋ねる必要があります。Do while loop with Character input
ほとんどの場合、ユーザーはCapsLockに注意を払わないため、プログラムははいの答えとしてYまたはyを受け入れる必要があります。しかし、私がこのプログラムを実行するたびに、私がY/Yに入っても、それは終了します!
私はGoogleで検索して、問題が原因new line
文字が私の文字入力を受け入れてもらうには可能性が出てたので、私は改行文字に対応するためにscanf("%c ", &choice);
へscanf("%c", &choice);
からscanfのコードを変更しますが、私のプログラムはまだ終了しつつありますY/yを入力として受け入れた後
ここにコードがあります。可能であれば、これらの問題に対処するためのベストプラクティスと方法を必要な修正とともにお知らせください。
#include<stdio.h>
#include"Disablewarning.h" // header file to disable s_secure warning in visual studio contains #pragma warning (disable : 4996)
void main() {
int factorial=1;//Stores the factorial value
int i; //Counter
char choice;//stores user choice to continue or terminte the program
do {//Makes sure the loop isn't terminated until the user decides
do{
printf("Enter the no whose factorial you want to calculate:\t");
scanf("%d", &i);
} while (i<0);
if (i == 0) //calculates 0!
factorial = 1;
else {//Calculates factorial for No greater than 1;
while (i > 0) {
factorial = factorial*i;
i--;
}
}
printf("\nThe factorialof entered no is :\t%d", factorial);//prints the final result
printf("\nDo you want to continue (Y/N)?");
scanf("%c ", &choice);
} while (choice =="y" || choice =="Y"); // Checks if user wants to continue
}
'として間違った答えを与える再計算} while(choice == "y" || –
'' Y ''は' char'へのポインタですが、 '' Y' 'は '' char''へのポインタです。 ''は単なる 'char'です。 – ForceBru
@Biffenオススメです。私はタグを削除する必要がありますか? –