Reputation: 5
I have this program, and I felt like I had finally made my code correct, but my output would never print my asterisks. A buddy of mine told me to run it through another compiler. I used JDoodle and my code worked perfectly. No matter what, I can't get it to run properly in Visual Studio. I updated it and everything. Anyone have any advice at all? I'll leave my code here, and would love to know if it has issues in someone elses Visual Studio, or if I am having issues with my compiler. Thanks in advance.
#include <iostream>
#include <iomanip>
#include <cmath>
using namespace std;
int* histo(int* scores, int count);
double dev(int count, int* scores);
double mean(int count, int* scores);
int main()
{
int scores[101];
int count = 0;
cout << "Enter a score (-1 to stop): ";
do
{
cin >> scores[count++];
} while (scores[count - 1] != -1);
count--;
int* bins = histo(scores, count);
for (int i = 9; i >= 0; i--)
{
cout << i << "| ";
for (int j = 0; j < bins[i]; j++)
{
cout << "*";
}
cout << endl;
}
delete[] bins;
cout << "mean: " << mean(count, scores) << endl;
cout << "dev: " << dev(count, scores) << endl;
system("pause");
return 0;
}
int* histo(int* scores, int count)
{
int* bins = new int[10];
for (int i = 0; i < count; i++)
{
if (scores[i] < 10)
{
bins[0]++;
}
else if (scores[i] >= 10 && scores[i] < 20)
{
bins[1]++;
}
else if (scores[i] >= 20 && scores[i] < 30)
{
bins[2]++;
}
else if (scores[i] >= 30 && scores[i] < 40)
{
bins[3]++;
}
else if (scores[i] >= 40 && scores[i] < 50)
{
bins[4]++;
}
else if (scores[i] >= 50 && scores[i] < 60)
{
bins[5]++;
}
else if (scores[i] >= 60 && scores[i] < 70)
{
bins[6]++;
}
else if (scores[i] >= 70 && scores[i] < 80)
{
bins[7]++;
}
else if (scores[i] >= 80 && scores[i] < 90)
{
bins[8]++;
}
else if (scores[i] >= 90)
{
bins[9]++;
}
}
return bins;
}
double dev(int count, int* scores)
{
double x = 0;
double y = 0;
double std_dev = 0;
double mean_t;
mean_t = mean(count, scores);
for (int i = 0; i < count; i++)
{
x = pow(scores[i] - mean_t, 2);
y += x;
}
std_dev = sqrt(y / count);
return std_dev;
}
double mean(int count, int* scores)
{
double total = 0;
for (int i = 0; i < count; i++)
{
total += scores[i];
}
return total / count;
}
Upvotes: 0
Views: 71
Reputation: 36082
You seem to assume that automatic variables on stack/heap are initialized to 0, they are not. E.g. int* bins = new int[10];
gives you an array of 10 uninitialized integers that could have any value, which could explain why it works with one compiler and the other not.
So potentially your histo
function will return an array with garbage. e.g. -1, -1337, ...
Upvotes: 4