Reputation: 61
Ok so everything is working except that the sorted data is sometimes outputting whole numbers rather than a decimal number. This seems like an easy mistake to fix, but I can't find it!
#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;
}
In an example run, the result is:
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
Upvotes: 0
Views: 753
Reputation: 131
If you use "i" only as counter then you can declare it inside the for loop such as
for (int i=0;i<length;i++)
This will save some trouble. Anyway,
Change
int i, temp;
to
int i;
double temp;
Double means it can hold decimal numbers, integer means whole numbers. When you are swapping around to do the bubble sort, it is converting your double to integer type. Your compiler should given a type conversion error, but should compile.
Upvotes: 1
Reputation: 2355
Try this:
double tmp;
std::cout << ios_base::setpercision(3) << tmp;
Upvotes: 0
Reputation: 89185
temp
should be a double
, not an int
, if you don't want things you assign to it to become integers.
Upvotes: 4