返回时更改double的C++值

C++ value of double is changed when returned

本文关键字:C++ double 返回      更新时间:2023-10-16

C++和学习的新手。此程序返回正确的输出。我将函数原型更改为void,以隔离并确保函数提供正确的输出。

#include <iostream>
#include <fstream>
void ArraySortToMedian(int x[], int numElem); 
using namespace std;
int main() 
{
    ifstream infile;
    infile.open("numbers.txt");
    const int SIZE = 6;
    int array[SIZE];
    int i;
    if(!infile)
    {
        cout << "couldn't find 'numbers.txt'";
        return 1;   
    }
    while(i < SIZE && infile >> array[i])
        i++;
    infile.close();
    for(i = 0; i < SIZE; i++)
        cout << array[i] << "n"; 
    ArraySortToMedian(array, SIZE);
    return 0;
}
void ArraySortToMedian(int x[], int numElem)
{
    bool swap;
    int temp, i;
    double m;
    do
    {
        swap = false;
        for(i = 0;i < (numElem - 1); i++)
        {
            if( x[i] > x[i + 1] )
            {
                temp = x[i];
                x[i] = x[i + 1];
                x[i + 1] = temp;
                swap = true;
            }
        }
    }
    while (swap);
    cout << "n";
    for(i = 0; i < numElem; i++)
        cout << x[i] << "n";
    m = (x[numElem/2] + x[numElem/2]-1)/(double)2;
    cout << "n" << m;
}

输出:

6
5
3
1
2
4
1
2
3
4
5
6
3.5

当我删除void并将其替换为double以返回main()时,中值如下。

#include <iostream>
#include <fstream>
double ArraySortToMedian(int x[], int numElem); 
using namespace std;
int main() 
{
    ifstream infile;
    infile.open("numbers.txt");
    const int SIZE = 6;
    int array[SIZE];
    int i;
    double median;
    if(!infile)
    {
        cout << "couldn't find 'numbers.txt'";
        return 1;   
    }
    while(i < SIZE && infile >> array[i])
        i++;
    infile.close();
    for(i = 0; i < SIZE; i++)
        cout << array[i] << "n"; 
    median=ArraySortToMedian(array, SIZE);
    cout<< "n" << median << "n";
    return 0;
}
double ArraySortToMedian(int x[], int numElem)
{
    bool swap;
    int temp, i;
    double m;
    do
    {
        swap = false;
        for(i = 0;i < (numElem - 1); i++)
        {
            if( x[i] > x[i + 1] )
            {
                temp = x[i];
                x[i] = x[i + 1];
                x[i + 1] = temp;
                swap = true;
            }
        }
    }
    while (swap);
    cout << "n";
    for(i = 0; i < numElem; i++)
        cout << x[i] << "n";
    m = (x[numElem/2] + x[numElem/2]-1)/(double)2;
    return(m);
}

失真输出:

1
6
5
3
1
2
1
1
2
3
5
6
2.5

当返回时,它移动在main()中生成的数组元素,而之前我只是从ArraySortToMedian()输出。我认为这与我引用数组第一个元素的起始地址有关。可能很简单,但由于我的经验有限,我对这种行为感到不知所措。任何帮助我了解自己做错了什么的人都将不胜感激。非常感谢。

问题在于您的输入循环:

int i;
// ... snip ...
while(i < SIZE && infile >> array[i])
    i++;

您从未初始化过i,所以这是未定义的行为。也许它有效,也许它不起作用。


如果使用std::vector而不是数组,这会更容易:

std::vector<int> values;
int next;
while (infile >> next) {
    values.push_back(next);
}

现在,您既不受大小限制,也不必担心跟踪索引。