帮我看一下C++一例结果为何跟我要求不一样?

来源:百度知道 编辑:UC知道 时间:2024/05/28 19:32:45
#include "stdafx.h"
#include <iostream>
#include <string>
using namespace std;

int main(int argc, char* argv[])
{
int i,j;
int mid;
int a[10];
cout<<"Please insert ten integer numbers:"<<endl;
for(i=0;i<10;i++)
cin>>a[i];
for(i=0;i<9;i++)
for(j=i+1;j<10;j++)
if(a[i]>a[j])
{
mid=a[i];
a[i]=a[j];
a[j]=mid;
}
cout<<"After exchange the data,the root is:"<<endl;
for(i=0;i<10;i++)
{
if(i=9) cout<<a[i];
if(i<9) cout<<a[i]<<";";
}
cout<<endl;

return 0;
}
结果为:
Please insert ten integer numbers:
23
65
789
346
975
345
863
658
26
450
After exchange the data,the root is:
975
Press any key to continue
为何不

解决:把i=9改成i==9就可以了.
解释:
你的排序算法是对的,不过效率不是很高,错误是你在输出的时候有一个判断语句if(i=9) cout<<a[i]; 这个条件错了,C++里面判断等于是用双等号==,所以你这条语句改成if(i==9) cout<<a[i]; 就可以了,要不要那个是赋值语句i一下子就=9,就输出了一下就退出循环了.要有比较好的效率,请看冒泡排序,及改进法.上网找一下就有很多介绍.

这种错误在C++/C里面是经常犯的,有一个方法可以减少这种错误,在编译的时候会被找到就是你把常数写在前面,养成一个习惯就不会了,如你上面那个if(i=9) cout<<a[i]; 如果你养成习惯了就会写if(9=i) cout<<a[i];那这样子就编译就会错了,你就知道改成if(9==i) cout<<a[i]; 希望对你有帮助.