#include <stdio.h> int main(){ int nums[10] = {1, 10, 6, 296, 177, 23, 0, 100, 34, 999}; int i, num, thisindex = -1; printf("Input an integer: "); scanf("%d", &num); for(i=0; i<10; i++){ if(nums[i] == num){ thisindex = i; break; } } if(thisindex < 0){ printf("%d isn't in the array.\n", num); }else{ printf("%d is in the array, it's index is %d.\n", num, thisindex); } return 0; }运行结果:
Input an integer: 100↙
100 is in the array, it's index is 7.
Input an integer: 28↙
28 isn't in the array.
#include <stdio.h> int main(){ int nums[10] = {0, 1, 6, 10, 23, 34, 100, 177, 296, 999}; int i, num, thisindex = -1; printf("Input an integer: "); scanf("%d", &num); for(i=0; i<10; i++){ if(nums[i] == num){ thisindex = i; break; }else if(nums[i] > num){ break; } } if(thisindex < 0){ printf("%d isn't in the array.\n", num); }else{ printf("%d is in the array, it's index is %d.\n", num, thisindex); } return 0; }与前面的代码相比,这段代码的改动很小,只增加了一个判断语句,也就是 12~14 行。因为数组元素是升序排列的,所以当 nums[i] > num 时,i 后边的元素也都大于 num 了,num 肯定不在数组中了,就没有必要再继续比较了,终止循环即可。
本文链接:http://task.lmcjl.com/news/5446.html