注册 登录
编程论坛 C++教室

怎么整理数列

xxm61424 发布于 2013-05-06 02:03, 608 次点击
Your program will do the following:
1. Read in a positive integer n representing the number of values the user will enter.
2. Then read in n double values into an array. You may assume that n <= 1000, i.e., the
user will enter at most 1000 numbers.
3. Use an algorithm discussed in class to sort this array from smallest to largest.
4. Then print out for each distinct value (from smallest to largest), how many times it
appeared in the sequence.
这是国外大学的一个作业,小弟只会把数列以顺序的形式来输出,但是这个要求把数列里面的相同元素分为一类,然后再输出,我是第一次学这个,完全不懂,希望大家能帮个忙,
#include <iostream>
using namespace std;
int main () {
    int i;
    int n;
    int j;
    double decimal[1000];
    int counter;               
    int index;
    double temp;
    int constant = 0;
    cout << "Enter a positive integer:" << "\n";
    cin >> n;
    cout << "Enter " << n << " numbers:" << "\n";
        for (i = 0; i < n; i = i + 1) {
            cin >> decimal[i];
        }
        for (i = 0; i < n-1; i = i + 1) {
        index = i;
        for (j = i + 1; j < n; j = j + 1) {
            if (decimal[index] > decimal[j]) {
                index = j;
            }
        }
        temp = decimal[i];
        decimal[i] = decimal[index];
        values[index] = temp;
    }
        for (counter = 0;counter < n) {
            for (i = 0;i < n;i = i + 1) {
               
      
        
               
return 0;
}
这是我写完的一段,我现在在想接下来怎么写,
3 回复
#2
xxm614242013-05-06 02:10
求大家了,我以前完全没学过啊,
#3
azzbcc2013-05-06 07:05
要用到三个数据类型 double data[1000],int count[1000] = {0}, int ip = 0;

dta存储出现的数据,count存储出现次数,ip表示当前位置

然后遍历数组。
#4
rjsp2013-05-06 08:43
程序代码:
include <vector>
#include <algorithm>
#include <iostream>

int main()
{
    size_t n;
    std::cin >> n;
    if( !std::cin || n==0 )
        return 1;

    std::vector<double> ds;
    ds.resize( n );

    for( size_t i=0; i!=n; ++i )
        std::cin >> ds[i];

    std::sort( ds.begin(), ds.end() );

    // 以下这段代码就是你需要的
    {
        double pre = ds[0];
        size_t count = 1;

        for( size_t i=1; i<n; ++i )
        {
            if( ds[i] == pre )
                ++count;
            else
            {
                std::cout << pre << '\t' << count << '\n';

                pre = ds[i];
                count = 1;
            }
        }

        std::cout << pre << '\t' << count << std::endl;
    }

    return 0;
}
1