更新时间:2016-08-22 22:53:53浏览次数:1+次
这是代码,但是我对于int main()中的表达,理解不了;还有while判断语句中的(!sign)表示的含义也不懂。麻烦了,谢谢;
#include <iostream>
using namespace std;
int main()
{
const int n=7;
int i,number,top,bott,mid,loca,a[n];
bool flag=true,sign;
char c;
cout<<"enter data:"<<endl;
cin>>a[0];
i=1;
while(i<n)
{cin>>a[i];
if (a[i]>=a[i-1])
i++;
else
cout<<"enter this data again:";
}
cout<<endl;
for(i=0;i<n;i++)
cout<<a[i]<<" ";
cout<<endl;
while(flag)
{
cout<<"input number to look for:";
cin>>number;
sign=false;
top=0;
bott=n-1;
if((number<a[0])||(number>a[n-1]))
loca=-1;
while((!sign)&&(top<=bott))
{
mid=(bott+top)/2;
if(number==a[mid])
{
loca=mid;
cout<<"Find"<<number<<",its position is"<<loca+1<<endl;
sign=true;
}
else if(number<a[mid])
bott=mid-1;
else
top=mid+1;
}
if(!sign||loca==-1)
cout<<number<<"has not found."<<endl;
cout<<"continu or not(Y/N)?";
cin>>c;
if(c==''''N''''||c==''''n'''')
flag=false;
}
return 0;
}
bool flag=true,sign;
这里一次性声明了两个bool变量,flag同时还初始化了。sign没有初始化。不过在第一层while循环中被赋值为false,并作为第二层while的一个检测条件。也就是提问中的(!sign)。while(i<n)
{
cin>>a[i];
if (a[i]>=a[i-1])
i++;
else
cout<<"enter this data again:";
}
那岂不是在第二次输入的时候覆盖第一次输入的值了呢!而且,紧接着的if判断,a[i]和a[i-1]的比较,在开始只有两个数字的时候,必然是a[0]和a[1]。所以,如果i不从1开始赋值,就无法完成开始的这个比较。while(i<n)
{
cin>>a[i];
if (a[i]<=a[i-1])
i++;
else
cout<<"enter this data again:";
}
那么得到的就是一组依次变小的数字,也就是降序排列数字,前者是升序排列数字。紧接的循环就是将数组依次输出。相关资讯