我在课堂上做的一个程序有问题,甚至老师也找不到问题。我们正在做一个程序,要求用户输入 double 然后当他停止时,它会扫描数组并将正负分开以将它们放在不同的数组中。
我们注意到,当我们使用 float 时,程序可以处理更多的数字,但如果我们输入太多,仍然会出错,如果我们在只输入几个数字后使用 double it 就会出错。我的意思是,程序运行良好,但是当它显示结果时,数组中有一些奇怪的数字。这是使用双精度的代码:
#include <iostream>
using namespace std;
void filling(double *, int &);
void sortPositiveNegative(double *, double *, double *, int, int &, int &);
void display(const double *, int);
int main () {
double * vecteur = new double;
double * positive = new double;
double * negative = new double;
int counter = 0, counterPos = 0, counterNeg = 0;
cout << "Filling of the real number vector " << endl;
filling(vecteur, counter);
cout << endl << "Display of the real number vector " << endl;
display(vecteur, counter);
cout << endl << "Sort of the positive and negative in the real number vector: " << endl;
sortPositiveNegative(vecteur, positive, negative, counter, counterPos, counterNeg);
cout << endl << "Display of the positive real number : " << endl;
display(positive, counterPos);
cout << endl << "Display of the negative real number : " << endl;
display(negative, counterNeg);
system("PAUSE");
return 0;
}
void filling (double *vecteur, int &counter)
{
bool validation;
char choice = 'Y';
do
{
do
{
validation = true;
cout << "Please enter the value of case " << counter+1 << ": ";
cin >> vecteur[counter];
if(cin.fail())
{
cerr << "The number entered is not valid." << endl;
cin.clear();
validation = false;
}
while(cin.get() != '\n'){}
}while(!validation);
counter++;
do
{
validation = true;
cout <<"Do you wish to continue? (Y/N): ";
cin >> choice;
if(toupper(choice) != 'Y' && toupper(choice) != 'N')
{
cerr << "We don't understand your choice, please try again." << endl;
cin.clear();
validation = false;
}
while(cin.get() != '\n'){}
}while(!validation);
}
while(toupper(choice)=='Y');
}
void sortPositiveNegative(double *vecteur, double *positive, double *negative, int counter, int &counterPos, int &counterNeg)
{
int i = 0;
for(i; i<counter;i++)
{
if(vecteur[i] >= 0)
positive[counterPos++] = vecteur[i];
else
negative[counterNeg++] = vecteur[i];
}
}
void display (const double *vecteur, int counter)
{
for(int i = 0; i<counter;i++)
cout << vecteur[i]<<endl;
cout << endl;
}
我的老师认为这可能是记忆问题,但我们不知道为什么会这样。
提前致谢。