这是关于在数组中寻找某个数(answer)的下标的程序的两种写法,结果却截然不同,由此引发了对if语句的进一步思考。
写法一:
#include<stdio.h>
int main()
{
int arr[] = { 1,2,3,4,5,6,7,8,9,10 };
int left = 0;
int right = sizeof(arr) / sizeof(arr[0])-1;
int mid=0;
int answer = 7;
int count = 1;
while (left <= right)
{
int mid = (left + right) / 2;
if(arr[mid]>answer)
{
right = mid - 1;
count++;
}
else if (arr[mid] < answer)
{
left = mid + 1;
count++;
}
else
{
printf("找到了在下标%d", mid);
break;
}
}
printf("\n找了%d次", count);
return 0;
}
输出结果:
写法二:
#include<stdio.h>
int main()
{
int arr[] = { 1,2,3,4,5,6,7,8,9,10 };
int left = 0;
int right = sizeof(arr) / sizeof(arr[0])-1;
int mid=0;
int answer = 7;
int count = 1;
while (left <= right)
{
int mid = (left + right) / 2;
if(arr[mid]>answer)
{
right = mid - 1;
count++;
}
if (arr[mid] < answer)
{
left = mid + 1;
count++;
}
else
{
printf("找到了在下标%d", mid);
break;
}
}
printf("\n找了%d次", count);
输出结果:
总结:两次写法类似,只是在第十九行if与if else不同,但是输出结果却不同,原因是我忽略了:
if... if....
和 的区别,
if... else if...
第一种是分别判断按照顺序执行,第二种是先判断第一句若成立就不进行下一步判断,若不成立就进行下一步判断
标签:语句,count,arr,int,mid,思考,answer,几点,left From: https://blog.51cto.com/u_15923331/5982097