### problem with my code

here is my code, when I run it it wont calculate the average. Also I dont know how to make the average and length have only 4 digits after the decimal. thanks

#include<stdio.h>
#include<stdlib.h>
#include<math.h>
using namespace std;

int find_max(int *Myarray,int n){
int i,max=Myarray[0];
for(i=1;i<n;i++)
if(Myarray[i]>Myarray[i-1])
max=Myarray[i];
return max;
}

int find_min(int *Myarray,int n){
int i,min=Myarray[0];
for(i=1;i<n;i++)
if(Myarray[i]<Myarray[i-1])
min=Myarray[i];
return min;
}

int find_average(int *Myarray,int n){
int i,sum=0;
int avg;
for(i=0;i<n; i++)
sum+=Myarray[i];
avg=sum/n;
return avg;
}

double find_length(int *Myarray,int n){
int i,sum=0;
double len;
for(i=0;i<n;i++)
sum+=Myarray[i]*Myarray[i];
len=sqrt(double(sum));
return len;
}

int main(){
int i,n,*Myarray;
printf("How many values do you want to \nenter?\n");
scanf("%d",&n);
Myarray=(int *)malloc(n*sizeof(int));
printf("Enter the values separated by one\n space\n");
for(i=0;i<n;i++)
scanf("%d",&Myarray[i]);
printf("You entered:\n");
for(i=0;i<n;i++)
printf("%d ",Myarray[i]);
printf("\nMax Entered:%d\n",find_max(Myarray,n));
printf("Min Entered:%d\n",find_min(Myarray,n));
printf("Average:%f\n",find_average(Myarray,n));
printf("Length:%f\n",find_length(Myarray,n));

system ("pause");
return 0;
}
Please use code tags ( <> button ) when posting code.

The average isn't calculated correctly because you use integers for it. And if a number with decimals is stored in an integer, the part behind the point is dropped. So use double's or floats.

 Also I dont know how to make the average and length have only 4 digits after the decimal.

You can use the std::setprecision() function: `std::cout << std::setprecision( 4 ) << etc...;`. To use setprecision(), you have to include <iomanip>.
Last edited on
Thank you!
Topic archived. No new replies allowed.