這是我的代碼的第一部分。輸入了 5 個數字的陣列。然后它將它們寫出并累積它們。
如果未輸入數字,我想使用 goto TAG 重新進入回圈。問題是當 for 回圈被非數值中斷并寫入“那不是數字”時,我沒有被要求輸入另一個值 - 它只是進入無限回圈。
我該如何解決?
int main(){
double i;
const int ARRAYSIZE = 5;
double array1[ARRAYSIZE];
double array2[ARRAYSIZE];
TAG:
printf("Input a total of %d. numbers.\n", ARRAYSIZE);
printf("The numbers will be accumulated:\n");
fflush(stdout);
for(int i = 0; i < ARRAYSIZE; i ){
if(scanf("%lf", &array1[i]) != 1)
{
printf("That is not a number - try again\n");
goto TAG;
}
}
uj5u.com熱心網友回復:
對于初學者這個變數和這個陣列
double i;
double array2[ARRAYSIZE];
程式中未使用。
使用該goto陳述句是一種糟糕的編程習慣。
例如,您的代碼可以通過以下方式重寫
#include <stdio.h>
int main(void)
{
enum { ARRAYSIZE = 5 };
double array1[ARRAYSIZE];
printf( "Input a total of %d. numbers.\n", ARRAYSIZE );
puts( "The numbers will be accumulated:" );
for ( int i = 0; i < ARRAYSIZE; i )
{
int success;
while ( ( success = scanf( "%lf", array1 i ) ) != 1 )
{
printf("That is not a number - try again\n");
scanf( "%*[^\n]%*c" );
}
}
for ( int i = 0; i < ARRAYSIZE; i )
{
printf( "%f ", array1[i] );
}
putchar( '\n' );
return 0;
}
程式輸出可能看起來像
Input a total of 5. numbers.
The numbers will be accumulated:
1
A
That is not a number - try again
2
B
That is not a number - try again
3
C
That is not a number - try again
4
D
That is not a number - try again
5
1.000000 2.000000 3.000000 4.000000 5.000000
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/336539.html
上一篇:有條件的測驗柏樹
