请使用VC6或使用【答题】菜单打开考生目录proj3下的工程文件proj3,此工程包含一个源程序文件proj3.cpp,其功能是从文本文件in.dat中读取全部整数,将整数序列存放到intArray类的对象myArray中,然后对整数序列按非递减排序,最后

admin2017-02-21  28

问题 请使用VC6或使用【答题】菜单打开考生目录proj3下的工程文件proj3,此工程包含一个源程序文件proj3.cpp,其功能是从文本文件in.dat中读取全部整数,将整数序列存放到intArray类的对象myArray中,然后对整数序列按非递减排序,最后由函数writeToFile选择序列中的部分数据输出到文件out.dat中。文件in.dat中的整数个数不大于300个。
    要求:
    补充编制的内容写在“//**********333**********”与“//********666********”两行之间。实现对整数序列按非递减排序,并将排序结果在屏幕上输出。不得修改程序的其他部分。
    注意:程序最后已将结果输出到文件out.dat中。输出函数writeToFile已经给出并且调用。
//proj 3.cpp
#include<iostream>
#include<fstream>
#include<cstring>
USing namespace std;
class intArray
{
private:
  int *array;//整数序列首地址
  int length;//序列中的整数个数
public:
  //构造函数,从文件中读取数据用于初始化新对象。参数是文件名
  intArray(char *filename);
  void sort();//对整数序列按非递减排序
  ~intArray();
  void  writeToFile  (char  *filename);
};
intArray∷intArray(char  *
filename)
{
  i fstream myFile(filename);
  int len=300;
  array=new int[fen];
  length=0;
  while(myFile>>array[length++]);
  length--;
  myFile.close();
    }
    void intArray∷sort(){
    //*************333*************
    //*************666*************
    }
    intArray∷~intArray()
    {
  delete[]array;
    }
    void  intArray∷writeToFile
    (char *filename)
    {
  int step=0;
  ofstream outFile(filename);
  for(int i=0;i<length;i=i+step)
    {
    outFile<<array<<end1;
    step++;
    }
    outFile.close();
  }
  void main()
  {
  intArray myArray("in.dat");
  myArray.sort();
  myArray.writeToFi le("out.dat");
}

选项

答案for(int i=0;1<length;++i) //遍历整个数组 for(int j=i;j<length;++j) //从i++遍历整数组 if(array[i]>array[j]) //如果arrag[i]>array[j],把array[i]与array[i]进行对换 { int temp; //定义一个临时变量temp temp=array[i]; //把array[i]值放到变量temp array[i]=array[j]; //把array[j]值赋给array[i] array[j]=temp; //把变量temp存放在值array[j]中 } for(int a=0;a<length;++a) //遍历数组,把数组中的所有元素打印到控制台上 cout<<array[a]<<" ";

解析 题目要求对整数序列按非递减排序,要排序就必须要有比较,因此定义两个下标i和j,按题目非递减排序要求,当array比array[j]大时就交换其值,利用中间变量temp来实现。
转载请注明原文地址:https://jikaoti.com/ti/N5t0FFFM
0

最新回复(0)