Working on a C++ program for a M*N dimension Matrix. The elements can't be more than three digits-I got that down-.I have most of the code done but, I'm having some problems on getting the average of the digits for each element & the quantity of digits for each elements...And I'm not sure the averageDigits thing is a go..... So,any help or input on anything would be appreciated thanks!
#include <iostream>
#include <stdlib.h>
using namespace std;
//prototypes
void read(int f, int c);
double average(int s);
void show(int f, int c);
double averageDigits(int n);
//global definitions
int i,j,A[100][100],n,m,sum=0;
double avg,ndigits;
int main()
{
cout<<"type number of rows---->";
cin>>n;
cout<<"type number of columns---->";
cin>>m;
read(n,m);
cout<<"\n\nThe Average of the Elements Is---->" <<average(sum)<<endl;
show(n,m);
cout<<"\nThe Avererage of the Digits of Each Element--->"<<averageDigits(sum/ndigits)<<endl;
cin.get();
return 0;
}
void read(int f,int c)
{
for(i=0;i<f;i++){
for(j=0;j<c;j++){
cout<<"A["<<i<<"]["<<j<<"]:";
cin>>A[i][j];
sum +=A[i][j];
if(A[i][j]<=999)
continue;
else
cout<<"\nInvalid Option...Try Again";
exit(EXIT_FAILURE);
}
}
}
double averageDigits(int n)
{
if (n < 0) n = -n; // quick n=abs(n)
if (n < 10) return (double)n; // quick average of a 1-digit number
int sum=0, ndigits = 0;
do {
++ndigits; // count digits
sum += n % 10; // add low digit of n to sum
n /= 10; // then delete low digit of n
} while (n > 0);
return (double)sum / ndigits;
I used floor(log10())+1 to get the number of digits in each field and sum them up. You may find it in math.h library. If you don't like that you may use a while loop by dividing by 10, chech n<? ... again for each field. Which is in your case (max 3000 runs) ok.
I think the way you are trying is not secure since 1+999=1000 and 500+500=1000. Left uses only 4 digits while the right uses 6.
ps check that you do not put double values into int functions.