0

好的,除了排序的数据有时输出整数而不是十进制数之外,一切正常。这似乎是一个容易修复的错误,但我找不到它!

#include <iostream>

using namespace std;

void input (double x[], int length);
void copy (double source[], double dest[], int length);
void sort (double x[], int length);
void display (double x[], int length);
int main()
{
    double data[20];
    double sdata[20];
    int itemcount;

    cout << "Enter data item count <1-20>" << endl;
    cin >> itemcount;
    if ((itemcount < 1) || (itemcount > 20))
    {
        cout << "Class size is NOT within required range. The required range is 1 to 20." << endl;
        cout << "Bye." << endl;
        return (0);
    }
    input (data, itemcount);
    cout << "Original Data:" << endl;
    copy (data, sdata, itemcount);
    display (sdata, itemcount);
    sort (sdata, itemcount);
    cout << "Sorted Data" << endl;
    display (sdata, itemcount);

}

void input (double x[], int length)
{
    int i;
    for (i=0; i < length; i++)
    {
        cout << "Enter score" << endl;
        cin >> x[i];
    }
}

void copy (double source[], double dest[], int length)
{
    int i;
    for (i=0; i < length; i++)
    {
        dest[i] = source[i];
    }
}

void sort (double x[], int length)
{
    int i, temp;
    bool swapdone = true;
    while (swapdone)
    {
        swapdone = false;
        for (i=0; i < length-1; i++)
        {
            if (x[i] > x[i+1])
            {
                temp = x[i];
                x[i] = x[i+1];
                x[i+1] = temp;
                swapdone = true;
            }
        }
    }
}

void display (double x[], int length)
{
    int i;
    for (i=0; i < length; i++)
    {
        cout << x[i] << " ";
    }
    cout << endl;
}

在示例运行中,结果是:

Enter data item count <1-20>
5
Enter score
30.41
Enter score
63.25
Enter score
62.47
Enter score
40.25
Enter score
310.41
Original Data:
30.41 63.25 62.47 40.25 310.41
Sorted Data
30.41 40.25 62 63 310.41
4

4 回答 4

4

temp如果您不希望分配给它的东西变成整数,则应该是 a double,而不是a 。int

于 2012-05-17T18:48:36.473 回答
1

如果您仅使用“i”作为计数器,那么您可以在 for 循环中声明它,例如

for (int i=0;i<length;i++)

这将节省一些麻烦。反正,

改变 int i, temp;

int i;
double temp;

Double表示它可以保存十进制数,integer表示整数。当您交换进行冒泡排序时,它会将您的双精度类型转换为整数类型。您的编译器应该给出类型转换错误,但应该编译。

于 2012-12-11T14:52:04.880 回答
0

尝试这个:

 double tmp;
 std::cout << ios_base::setpercision(3) << tmp;
于 2012-05-17T18:49:50.180 回答
0

查看

int i, temp;

温度必须是两倍!

于 2012-05-17T18:51:56.607 回答