Friends in following code i am trying to get some of the average in float...i tried manually my ans should be in fraction, but here it comes in rounded fig...please help me.
#include <stdio.h>
#include <stdlib.h>
//finding out the average marks for students ....
float average (float []);
int main()
{
int i;
float total_avg=0;
float arr_1[] = {10.2, 22.9, 36.04, 89.1, 94.1, 10.8,};
for(i=0; i<6; i++)
printf("%2f\n",arr_1[i]);
printf("\n\n");
total_avg = average (arr_1);
printf("Total average : %3f\n",total_avg);
system("PAUSE");
return 0;
}
float average (float a[5])
{
int sum = 0, i;
float total;
for(i=0; i<6; i++)
{
sum = sum+a[i];
}
total = sum/5;
return total;
}
Once you've fixed the type of sum as pointed out by bash.d, your answer will still be wrong. arr_1 contains 6 elements but you divide by 5 when calculating the average. You need to change the calculation of total to
total = sum/6;
Or, better still, change average to
float average(float* a, int num_elems)
{
float sum = 0
int i;
for(i=0; i<num_elems; i++) {
sum += a[i];
}
return sum/num_elems;
}
and call average like
total_avg = average (arr_1, sizeof(arr_1)/sizeof(arr_1[0]));
Why use int as sum? Use float instead:
float average (float a[5])
{
int sum = 0,
float total, sum = 0.0f;
for(i=0; i<6; i++)
{
sum = sum+a[i];
}
total = sum/5;
return total;
}
Related
I tried to do something by combining functions, arrays and pointers, but I got this error, I couldn't figure out why, I would appreciate if you could help.
double findaverage(int howmany, *int grades[]);
#include <stdio.h>
double findaverage(int howmany, *int grades[]) {
int i;
int sum = 0;
for (i = 0; i < howmany; i++) {
sum = grades[i] + sum;
}
return sum / howmany;
}
int main()
{
const int size = 5;
int grades[5] = {30,56,23,44,45};
int average= findaverage(size, grades);
printf("%d", average);
return 0;
}
My interpretation on how to transform the comments into code.
removed obsolete prototype definition (it is obsolete due to function call order)
renamed function from findaverage to calculate_average due to what it does
changed *int grades[] to int grades[]
moved iterator declaration (int i) into loop as it is not used outside of the loop
changed type of sum from int to double
used += operation instead of sum = sum + ..., to keep the code short and expressive
changed type of average from int to double
added helper function to print input array
changed output type format, added two digital places and newline to output of average
add pointer versions of calculate_average to illustrate/clarify differences
The original data are structured as array. Therefore, they should be accessed in array style. Nevertheless, it is possible to process them in pointer style. See also the answers to What is the difference between char array and char pointer in C? for clarification.
calculate_average.c
#include <stdio.h>
double calculate_average(int howmany, int grades[]) {
double sum = 0.0;
for (int i = 0; i < howmany; i++) {
sum += grades[i];
}
return sum / howmany;
}
double calculate_average_pointers(int howmany, int *grades) {
double sum = 0.0;
for (int i = 0; i < howmany; i++) {
// calculate position of next int in memory 'grades + i' and
// retrieve int from it with dereference operator '*'
sum += *(grades + i);
}
return sum / howmany;
}
// working but bad mix of semantics, array as paramter, pointer arithmetic inside
double calculate_average_pointers_2(int howmany, int grades[]) {
double sum = 0.0;
for (int i = 0; i < howmany; i++) {
sum += *(grades + i);
}
return sum / howmany;
}
void print_array(int howmany, int grades[]) {
printf("[");
for (int i = 0; i < howmany; i++) {
char *comma_or_not = i < howmany - 1? "," : "";
printf(" %d%s", grades[i], comma_or_not);
}
printf(" ]\n");
}
int main()
{
const int size = 5;
int grades[5] = {30, 56, 23, 44, 45};
printf("Input: ");
print_array(size, grades);
double average = calculate_average(size, grades);
printf("Average: %.2lf\n", average); // two decimal places
average = calculate_average_pointers(size, grades);
printf("Average (pointers): %.2lf\n", average); // two decimal places
average = calculate_average_pointers_2(size, grades);
printf("Average (pointers 2): %.2lf\n", average); // two decimal places
return 0;
}
$ gcc -Wall calculate_average.c
$ ./a.out
Input: [ 30, 56, 23, 44, 45 ]
Average: 39.60
Average (pointers): 39.60
Average (pointers 2): 39.60
$
I finally got code that's giving me random floats from 0 to 1.
My code looks like this:
#include<stdio.h>
#include<stdlib.h>
#include<time.h>
int main()
{
srand((int)time(NULL));
int N=10;
float a = 1.0;
for (int i=0;i<N;i++)
printf("%f\n", ((float)rand()/(float)(RAND_MAX)) * a);
return 0;
}
Now, I need to make program that will give me the average from given numbers for 10<=N<=10000, but im out of ideas how to make it works. Any ideas?
Used the 'a' variable as temporary storage and summation for the floats.
#include<stdio.h>
#include<stdlib.h>
#include<time.h>
int main()
{
srand((int)time(NULL));
int lowerLimit = 10 + 1, upperLimit = 10000;
//generates random number between 10 and 10000, if needed
int N = lowerLimit + rand() % (upperLimit - lowerLimit);
/* 'a' variable was not needed in previous*/
float a, sum = 0.0;
for (int i=0;i<N;i++){
a = ((float)rand()/(float)(RAND_MAX));
sum += a;
printf("Float %i = %f\n", i,a);
}
printf("Average = %f\n", sum/N);
return 0;
}
Before printing, store them and sum them up.
int main()
{
srand((int)time(NULL));
int N=10;
float a = 1.0f, r, sum = 0.0f;
for (int i=0;i<N;i++){
r = ((float)rand()/(float)(RAND_MAX)) * a;
printf("%f\n", r);
sum += f;
}
printf("sum = %f\n", sum / N);
return 0;
}
I am bashing my head because I cannot figure out why my C code keeps printing the wrong average of a set of n numbers!
This is my code below:
int main()
{
int i;
int n;
int sum = 0.0;
int lowest;
int highest;
float average;
int range;
int middle;
double median;
printf("\nEnter the amount of numbers you want?\n");
scanf("%d",&n);
int numbs[n];
int temp[n];
for(i = 0;i < n; i++)
{
printf("\nEnter a number from 0 to 15: ");
scanf("%d",&temp[i]);
}
while (temp[i] < 0 || temp[i] > 15) than 15
{
printf("This number is not from 0 to 15! Please re-enter another number: ");
scanf("%d",&temp[i]);
}
numbs[i] = temp[i];
sum += numbs[i];
}
int sortt = 0, j, x;
for (x = 1; x < n; x++) {
for (j = 0; j < n - x; j++) {
if (numbs[j] > numbs[j + 1]) {
sortt = numbs[j];
numbs[j] = numbs[j + 1];
numbs[j + 1] = sortt;
}
}
}
lowest = numbs[0];
highest = numbs[n-1];
middle = n/2;
if (n % 2)
{
median = numbs[middle];
}
else
{
median = (numbs[middle - 1] + numbs[middle]) / 2.0;
}
average = sum/n;
range = highest - lowest;
printf("\nSum: %d", sum);
printf("\nAverage: %.2f", average);
printf("\nMedian: %.2f", median);
printf("\nRange: %d\n", range);
return 0;
}
This is my input and output below. You can see that 8 divided by 3 is not 2, it is 2.67! I've tried using double and float.
Input & Output:
You need to correct the following line:
average = sum/n;
to
average = (float)sum/n;
You have to cast your return value into float. Think about it as a function with the following definition:
float divide(int x,int y){
return x/y; // returns an integer instead of float.
}
While this definition:
float divide(int x,int y){
return (float)x/y; // creates a temporary float variable and returns it immediately as the returned value of the function.
}
In addition, declaring int sum=0.0 is definitely going to show you a warning when compiling with -Wall. Try to follow warnings that you get from your compiler and fix all of them before you run your program.
8 divided by 3 is 2, remainder 2. 8 and 3 are integers, and when you divide two integers, you use integer division with integer rules.
Also, this line might be confusing you:
int sum = 0.0;
Since sum is an int, this just sets sum to zero.
And:
average = sum/n;
Since both sum and n are integers, this is integer division. What you do with a result does not affect how that result is computed -- C's rules are complex enough already.
/*Here see you can intake all values as float instead */
#include <stdio.h>
#include <stdlib.h>
void main()
{
float i,n,a,b,sum,ave;
printf("This is a program to calculate the average of 'n' numbers \n");
printf("Of How many numbers do you want to calculate average \n");
scanf("%f", &n);
printf("Enter the first number \n");
scanf("%f", &a);
sum = a;
for (i=1;i<n;i++)
{
printf("Enter another number \n");
scanf("%f", &b);
sum = sum + b;
}
ave = (sum/n);
printf("The average of the %f number is %f", n, ave);
getchar();
}
#include<stdio.h>
#include<math.h>
int main()
{
int n;
scanf("%d",&n);
int i=0,sum=0,average=0;
int num[100]={0};
double dvalue[100]={0.0};
double variance=0.0,s=0.0;
for(i=0;i<n;i++){//I just know this method to get the number array;
scanf("%d",&num[i]);
sum+=num[i];
}
average=sum/n;
for(i=0;i<n;i++){
dvalue[i]=num[i]-average;
dvalue[i]=pow(dvalue[i],2.0);//to get the (x-average)……2
variance+=dvalue[i];
}
s=sqrt(variance);
return 0;
}
this is my code,but it can't get the right answer.I am a new learner and this is the first time I seek help via stackoverflow I can't get the output why?
Thanks for every one .I actually debug at first ,but I can't know how to modify it ,sincerely thanks again
There were two things to correct:
1. type of average should be double
2. you have taken the variance incorrectly. after taking the sum of (x- average) you should divide it by n
#include<stdio.h>
#include<math.h>
int main()
{
int n;
scanf("%d", &n);
int i = 0, sum = 0;
double average = 0;
int num[100] = { 0 };
double dvalue[100] = { 0.0 };
double variance = 0.0, s = 0.0;
for (i = 0; i < n; i++) { //I just know this method to get the number array;
scanf("%d", &num[i]);
sum += num[i];
}
printf("sum %d\n", sum);
average = sum;
average = average / n;
printf("average %lf\n", average);
for (i = 0; i < n; i++) {
dvalue[i] = num[i] - average;
dvalue[i] = pow(dvalue[i], 2.0); //to get the (x-average)……2
variance += dvalue[i];
}
variance = variance / n; // population variance
s = sqrt(variance);
printf("varience %lf\n", variance);
printf("Population Standard deviation %lf", s);
return 0;
}
edited the answer according to #chux advice
#include <stdio.h>
#include <stdlib.h>
double calculate(int ar[], int npts, int *gtr);
int main()
{
int ar[4] = {1,2,3,0};
double result;
result = calculate(ar,4, &ar);
printf("%lf ",result );
return 0;
}
double calculate(int ar[], int npts, int *gtr)
{
double total =0;
int i = 0;
double average;
for(i=0; i<npts; i++)
{
total = total + ar[i];
}
average = total / npts;
return average;
for(i=0; i<npts; i++)
{
if(average < ar[i])
{
*gtr++;
}
}
return *gtr;
}
when i call function calculate i want to return both average and *gtr value
but avergage only average value return. *gtr is for counting how many numbers greater than average numbers in arrary.
from what i understand,you want to return the average,and somehow get the value of gtr.you can return the average value,and save the gtr value to another variable by using a pointer.
int main()
{
int ar[4] = {1,2,3,0};
double result;
int gtr = 0;
result = calculate(ar,4,>r);
printf("%lf\n",result );
printf("gtr : %d\n",gtr);
return 0;
}
double calculate(int ar[], int npts, int *gtr)
{
double total = 0 , average;
int i = 0;
for(i=0; i<npts; i++)
{
total = total + ar[i];
}
average = total / npts;
for( i = 0 ; i < npts ; i++ )
{
if(average < ar[i])
{
*gtr += 1;
}
}
return average;
}
You made the function almost right, it's the call that must be done differently.
First, don't return *gtr from the function; return average. Do it at the end, though, not in the middle.
Then, change the call to
int gtr;
result = calculate(ar,4, >r);
printf("%lf %d\n",result, gtr);
Make sure that you set *gtr to zero before the second loop, otherwise it would remain uninitialized.
For return both value you can do this:
double calculate(int ar[], int npts, int *gtr)
{
double total =0;
int i = 0;
double average;
for(i=0; i<npts; i++)
{
total = total + ar[i];
}
average = total / npts;
return average;
for(i=0; i<npts; i++)
{
if(average < ar[i])
{
*gtr++;
}
}
return avergage;
}
so, returning avergage you have the first variable, and using the puntator value of gtr you can have that value.