#include <stdio.h> #include <stdlib.h> int main(){ int nums[10] = {1, 10, 6, 296, 177, 23, 0, 100, 34, 999}; int i, num, subscript = -1; printf("Please input an integer: "); scanf("%d", &num); for(i=0; i<10; i++){ if(nums[i] == num){ subscript = i; break; } } if(subscript<0){ printf("%d isn't in the array.\n", num); }else{ printf("%d is in the array, and it's subscript is %d.\n", num, subscript); } system("pause"); return 0; }運行結果:
Please input an integer: 100
100 is in the array, and it's subscript is 7.
Please input an integer: 28
28 isn't in the array.
#include <stdio.h> #include <stdlib.h> int main(){ int nums[10] = {0, 1, 6, 10, 23, 34, 100, 177, 296, 999}; int i, num, subscript = -1; printf("Please input an integer: "); scanf("%d", &num); for(i=0; i<10; i++){ if(nums[i] >= num){ if(nums[i] == num){ subscript = i; } break; } } if(subscript<0){ printf("%d isn't in the array.\n", num); }else{ printf("%d is in the array, and it's subscript is %d.\n", num, subscript); } system("pause"); return 0; }注意第11行代碼,只有當 nums[i] >= num 成立時才進行處理,否則繼續循環。nums[i] >= num 有兩重含義: