[英]Checking the positivity of elements entered by the user in an array
我有一個程序要求用戶輸入將分配給數組的元素。 但我想檢查輸入的數字是正數還是負數。 如果有負數程序應該警告用戶並要求用戶再次輸入正數。 我寫了我的代碼,但它進入了無限循環。 怎樣才能正確呢?
這是我的代碼:
#include <stdio.h>
#include <stdlib.h>
#define MAX 100
int main()
{
int A[MAX] = {};
int n,jj;
printf("How many numbers do you want to enter?\n");
scanf("%d",&n);
for (jj=0; jj<n; jj++)
{
printf(" enter the %d. number\n", (jj+1));
scanf("%d",&A[jj]);
while(A[jj]<=0){
printf("Please enter only positive numbers");
}
}
return 0;
}
對於初學者來說,這個初始化使用一個空的花括號列表
int A[MAX] = {};
在 C 中是不正確的。你必須寫
int A[MAX] = { 0 };
很明顯,這個循環
while(A[jj]<=0){
printf("Please enter only positive numbers");
}
當A[jj]
不為正時是一個無限循環。 所以你所做的就是你得到的。
相反,你可以寫例如
for (jj=0; jj<n; jj++)
{
printf(" enter the %d. number\n", (jj+1));
do
{
scanf("%d",&A[jj]);
if ( A[jj]<=0 )
{
printf("Please enter only positive numbers");
}
} while ( A[jj] <= 0 );
}
死循環的原因是由於使用了while(A[jj]<=0)
該問題可以通過以下兩個步驟解決:
這是工作代碼:
#include <stdio.h>
#include <stdlib.h>
#define MAX 100
int main() {
int A[MAX] = {};
int n, jj, temp = 0;
printf("How many numbers do you want to enter?\n");
scanf("%d",&n);
for (jj = 0; jj < n; jj++) {
printf("Enter the # %d number : ", (jj+1));
scanf("%d",&temp);
if (temp < 0) {
printf("Negative number will not be accepted. Please try again\n");
--jj;
continue;
}
A[jj] = temp;
}
return 0;
}
Output:
How many numbers do you want to enter?
3
Enter the # 1 number : 1
Enter the # 2 number : -2
Negative number will not be accepted. Please try again
Enter the # 2 number : 2
Enter the # 3 number : 3
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.