Calculating the percentage of each of the numbers in the matrix

Hi there. In college I got this task
"Input integer matrix 3x5 with elements from 0 to 9. Calculate the percentage of
each of these numbers in the matrix." I'm not sure if code is right, so can somebody pls check it and correct mistakes?

[code]
#include <iostream>
#include <math.h>
using namespace std;
int main()
{
int a[3][5], i, j; double sum=0, P=0;
cout<<"Input matrix 3x5"<< endl;
for(i=0; i<3; i++)
for(j=0; j<5; j++)
{
cin >> a[i][j];
sum += a[i][j];
}

P=(15/sum)*100;
cout<<"\nThe sum of array elements is: "<< sum <<endl;
cout<<"\nThe percentage of each of these number is: "<< P <<endl;
system("pause");
return 0;
}
[code]
You call 15 / sum-of-values a "percentage".
Is that the percentage that you are looking for?

Each element could be 0. Their sum would be 0. How much is 15 / 0?

the percentage of each of these numbers in the matrix

Sounds like:
* How many elements have value 0?
* How many elements have value 1?
...
* How many elements have value 9?

Back to the "all 0" example: 15 out of 15 elements would be 0.
100% of the elements would have value 0.
Values 1-9 would occur in 0% of the elements.

Each of the values 0-9 would have its own percentage.

If you think that my interpretation is correct, then think what to do to your math.


What if I type 42 as the user? Should you validate the input?


PS.
* You have a typo in your code tag.
* Where do you use the <math.h>? Nowhere.
* If you would need math header, then do include <cmath>
1
2
3
4
5
6
7
8
int a[3][5];
...
map<unsigned short, unsigned short> b;
for (int j = 0; j < 3; j++)
	for (int i = 0; i < 5; i++)
		b[a[j][i]]++;
for (auto& p : b)
	cout << "Percentage of " << p.first << " is " << 100.0f * p.second / 15 << "%\n";

This?
Last edited on
Topic archived. No new replies allowed.