c++ 用二分法查数,出现问题了,求高手指点迷津?
#include<iostream>#definesize5usingnamespacestd;voidmain(){inti,j;floatt,a[size];for(...
#include<iostream>
#define size 5
using namespace std;
void main()
{
int i,j;
float t,a[size];
for(i=0;i<size;i++)
{
cout<<"a["<<i<<"]=";
cin>>a[i];
}
cout<<endl;
for(i=0;i<size-1;i++)
{
for(j=i+1;j<size;j++)
{
if(a[i]>a[j])
{
t=a[i];
a[i]=a[j];
a[j]=t;
}
}
}
for(i=0;i<size;i++)
{
cout<<"a["<<i<<"]=";
cout<<a[i]<<" ";
}
cout<<endl;
int value;
int found;
int low,mid,high;
cout<<"Enter the value of found: ";
cin>>found;
low=0;
found=0;
high=size-1;
while(low<=high)
{
mid=(low+high)/2;
if(value==a[mid])
{
found=1;
break;
}
else if(value<a[mid])high=mid-1;
else if(value>a[mid])low=mid+1;
if(found)cout<<"The value is: a["<<mid<<"]"<<endl;
}
if(found==0)cout<<"The value cann't find!"<<endl;
}
编译无错,排序也对,就是查不出想查的数,求高手点拨; 展开
#define size 5
using namespace std;
void main()
{
int i,j;
float t,a[size];
for(i=0;i<size;i++)
{
cout<<"a["<<i<<"]=";
cin>>a[i];
}
cout<<endl;
for(i=0;i<size-1;i++)
{
for(j=i+1;j<size;j++)
{
if(a[i]>a[j])
{
t=a[i];
a[i]=a[j];
a[j]=t;
}
}
}
for(i=0;i<size;i++)
{
cout<<"a["<<i<<"]=";
cout<<a[i]<<" ";
}
cout<<endl;
int value;
int found;
int low,mid,high;
cout<<"Enter the value of found: ";
cin>>found;
low=0;
found=0;
high=size-1;
while(low<=high)
{
mid=(low+high)/2;
if(value==a[mid])
{
found=1;
break;
}
else if(value<a[mid])high=mid-1;
else if(value>a[mid])low=mid+1;
if(found)cout<<"The value is: a["<<mid<<"]"<<endl;
}
if(found==0)cout<<"The value cann't find!"<<endl;
}
编译无错,排序也对,就是查不出想查的数,求高手点拨; 展开
1个回答
展开全部
/*
36 25 41 58 97
a[0] = 36
a[1] = 25
a[2] = 41
a[3] = 58
a[4] = 97
a[0] = 25 a[1] = 36 a[2] = 41 a[3] = 58 a[4] = 97
Enter the value of found: 41
The value is: a[2]
Press any key to continue
*/
#include<iostream>
#define size 5
using namespace std;
void main() {
int i,j;
float t,a[size];
for(i = 0;i < size;i++) {
cin >> a[i]; // 先输入,后显示
cout << "a[" << i << "] = " << a[i] << endl;
}
cout << endl;
for(i = 0;i < size - 1;i++) {
for(j = i + 1;j < size;j++) {
if(a[i] > a[j]) {
t = a[i];
a[i] = a[j];
a[j] = t;
}
}
}
for(i = 0;i < size;i++) {
cout << "a[" << i << "] = " << a[i] << " ";
}
cout << endl;
int value;
int found;
int low,mid,high;
cout << "Enter the value of found: ";
cin >> value;
low = 0;
high = size - 1;
while(low <= high) {
mid = (low + high) / 2;
if(value == a[mid]) {
found = 1;
break;
}
else if(value < a[mid]) high = mid - 1;
else low = mid + 1;
}
if(found)cout << "The value is: a[" << mid << "]\n";
else cout << "The value cann't find!\n";
}
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询