Wrong value output on simple average calculation in C - c

I am passing an array of exam grades to the examAverage function along with the size of the array. When I printf the array contents in the for loop they are correct, but when they are added together the sum is wrong. Even if I printf immediately after I set double sum = 0, it says sum = 2. By the time the function is complete I get an extremely large number. Any help is appreciated.
double examAverage(int arr[], int size){
int i;
double exAvg=0;
double sum =0;
printf("Sum = %d\n", sum);
for (i = 0; i < size; ++i)
{
printf("Sum = %d\n", sum);
sum = arr[i];
}
exAvg = sum / size;
return exAvg;
}
Main
double examAverage(int arr[], int size);
printf("How many exam grades would you like to enter?\n");
scanf("%d", &examGrad);
int exams[examGrad];
printf("Enter exam grades \n");
for(int i=0; i<sizeof(exams)/sizeof(exams[0]); i++){
scanf("%d", &exams[i]);
}
double exAvg;
exAvg= examAverage(exams, examGrad);
printf("Exam average = %d", exAvg);
Output
How many exam grades to enter?
2
Enter exam grades
100
50
Sum = 2
Sum = 10
Sum = 1079574528
Exam Average = 1081159680

Don't You mean sum += arr[i]; in the for loop in examAverage?
Also, Your code labeled Main is not really valid at all, first, there is no declaration of examGrad, second the function declaration at the top does whoever knows what, third, sizeofs in the for loop can be replaced by the examGrad, the %d was already mentioned.
If You ask questions about simple code just include all of it, If it is too much, cut out the unnecessary parts or ensure us that they are there, otherwise we don't know if the problem is the missing code or not.

Do not use %d to print a double; that is for integers. Use %f. The different way in which integers and floating point numbers are stored accounts for the problems that you are seeing.
You should have seen a warning about this when you compiled, along the lines of:
format specifies type 'int' but the argument has type 'double'

Related

Avergaging elements in array

I'm trying to add the elements in an array. It's just a simple program to calculate the average of student grades. I know this is probably a rudimentary way to code this, I'm looking to do it more efficiently. However my code is not returning the average. I would greatly appreciate any help. I did try this with a for loop but got the same incorrect answer.
#include <stdio.h>
int main()
{
int grades[6];
int average;
int sum = 0;
printf("Please enter your five test scores:\n");
scanf("%d", &grades[0]);
scanf("%d", &grades[1]);
scanf("%d", &grades[2]);
scanf("%d", &grades[3]);
scanf("%d", &grades[4]);
scanf("%d", &grades[5]);
sum = sum + grades[6];
average = sum / 5;
printf("The average of the students test scores is %d:\n", average);
return 0;
}
You should sum all grades and then divide by their amount (in your case it is 6 not 5, because grades array has 6 elements). Here is a code sample:
#include <stdio.h>
int main()
{
int grades[6];
int average;
int sum = 0;
printf("Please enter your six test scores:\n");
scanf("%d", &grades[0]);
scanf("%d", &grades[1]);
scanf("%d", &grades[2]);
scanf("%d", &grades[3]);
scanf("%d", &grades[4]);
scanf("%d", &grades[5]);
for (int i = 0; i < 6; i++)
sum = sum + grades[i];
average = sum / 6;
printf("The average of the students test scores is %d:\n", average);
return 0;
}
I'm trying to add the elements in an array.
This is maybe already a wrong track regarding the title (and the code) where it is about averaging elements in an array.
How you build the array is up to you; I choose the simplest way. An important decisions is: is size of array and number of values the same? That is what n_grades does. The four zeroes in the array initialization illustrate the difference.
An average most likely should be a floating point number.
A nasty problem with averages is the lurking overflow. Very unlikely in this setting, but there is a more robust (and elegant) algorithm. The (double) cast is the un-elegant part, but is needed because the division is between two integers. Still this is the compact core:
for (i = 0; i < n_grades; i++)
aver += (double) grades[i] / n_grades;
corresponding to the math formula:
i<n
A = Sum G_i/n
i=0
("Sum" is the big Sigma)
#include <stdio.h>
int main()
{
int grades[] = {10,10,9,10,11,11,0,0,0,0};
int n_grades = sizeof grades / sizeof*grades; // use all elements
//n_grades = 6; // use only first n elements
double aver = 0;
for (int i = 0; i < n_grades; i++)
aver += (double) grades[i] / n_grades;
printf("The average of the students test scores is %f (n= %d):\n",
aver, n_grades);
return 0;
}
Now it prints:
The average of the students test scores is 6.100000 (n= 10):
or, uncommented, i.e. limited to 6 grades::
The average of the students test scores is 10.166667 (n= 6):
You're assuming that grades[6] holds the sum of all the values in the grades array, which is wrong of course.
You need something like:
for (int i = 0; i < 6; i++)
sum = sum + grades[i];

Trouble with storing random number and Yes No loop

I have written a c code to generate random numbers(each time generate a different set of random numbers) and need to ask the user if want to generate another random number. If the user reply yes, the program need to generate another random number; if the user replies No, the program needs to calculate the total and average of the random numbers.
My problem is I don't know how to store the random number and there is a problem with my loops.
#include<stdio.h>
#include<stdlib.h>
#include<time.h>
main()
{
int sum=0, i, num[100], arr[100];
float avg;
char choice;
srand(time(0));
for(i=0; i<100; i++)
{
arr[i] = rand();
printf("Random number generated: %d", arr[i]);
fflush(stdin);
printf("\nGenerate another random number(y/n)? ");
scanf("%c", &choice);
if(choice == 'n' || choice == 'N')
{
sum += arr[i];
avg = sum / i;
printf("\n::TOTAL : %d", sum);
printf("\n::AVERAGE : %.2f", avg);
}
}
system("PAUSE");
}
The correct output should be like this:
Correct output
There are several issues with your code:
Add a break at the end of your "No"-condition to get out of the loop in that case.
Accumulate your sum (for the average) outside the "No"-condition.
To store you could simply run another loop for(int j=0; j<=i; ++j) printf("%d\t", arr[j]); and copy the output from the command line - or get yourself familiar with file IO.
By the way: sum is likely to overflow if you accumulate several numbers of the same data type.

For loop function too few arguments to function

Hi I'm somewhat very new to programming and I just came across this new error called "too few arguments to function" and have no idea what this means. I've been trying to figure out for a while whats exactly wrong with the code, but I'm having no luck so far. Any advice? Thanks in advance!
int sumRange(int lowerNumber, int higherNumber);
int main()
{
int lowerNumber,
higherNumber,
sum;
scanf("%d%d", lowerNumber, higherNumber);
printf("\nThe smaller number is %d and the larger number is %d", lowerNumber,higherNumber);
printf("\nThe sum number of all ranges for both numbers is: %d", sumRange(sum));
}
int sumRange(int lowerNumber, int higherNumber)
{
int x,
total;
for(x = lowerNumber; x <= higherNumber; x++)
{
total = total + x;
}
return x;
}
You have to initialize the "total".
int sumRange(int lowerNumber, int higherNumber)
{
int x,
total;
total = 0;
for(x = lowerNumber; x <= higherNumber; x++)
{
total = total + x;
}
return total;
}
Function main() lacks initial { and final }.
Also, in function sumRange, you may want to return total, not the x.
Also, in line "printf("\nThe sum number of all ranges for both numbers is: %d", sumRange(sum));"
you are calling sumRange with only one parameter. You should call it with two parameters: sumRange(lowerNumber,higherNumber)
I just came across this new error called "too few arguments to function" and have no idea what this means
It means that the function wasn't supplied all of the arguments that are present in its definition.
The function was defined here:
int sumRange(int lowerNumber, int higherNumber);
As you can see, there are two arguments in the definition: int lowerNumber, int higherNumber. But your use of that function here:
printf("\nThe sum number of all ranges for both numbers is: %d", sumRange(sum));
Only supplies that function with one argument. Since you are reading the arguments in with scanf, the correct use would be:
printf("\nThe sum number of all ranges for both numbers is: %d", sumRange(lowerNumber, higherNumber));

Infinite Recursion loop C

We have been learning about recursion vs iteration in C this week and we were required to make a program that recursively determines the value of the nth term of a geometric sequence defined by the terms a, ar, ar^2, ... ar^(n-q).
For the most part, I think I have it figured out, as it seems to display the correct values per run, but it doesn't manage to break the recursion when the tested value reaches zero. Also, if possible to get a better explanation of recursion, and some examples of when recursion would be preferred over iteration as I'm still struggling with the concept.
// 2/20/2018
//Lab 6 Solution for Page 369 PE 4 B
//including libraries to be used
#include <stdio.h>
#include <math.h>
int main() {
//Function prototype
double goAnswer(int *, double, double, double, double *, int);
//Declaring variables
int nValue = 0;
double ratio = 0;
double firstTerm = 0;
double answer = 0;
double addedAnswer = 0;
int count = 1;
//Setting up to ask for each value
printf("Please enter in the value of n: ");
scanf("%d", &nValue);
printf("Please enter in the ratio you'd like to use: ");
scanf("%lf", &ratio);
printf("Please enter in the first term to use: ");
scanf("%lf", &firstTerm);
addedAnswer = goAnswer(&nValue, ratio, firstTerm, answer, &addedAnswer,
count);
//Printing out the value of the first nth terms
printf("The value of all terms added together is: %lf\n", addedAnswer);
return 0;
}
//function header
double goAnswer(int *nValue, double ratio, double firstTerm, double answer,
double *addedAnswer, int count) {
if (nValue == 0){
return 0;
}
else{ //This part calculates the answer, prints the value to the screen,
adds the answer to a running sum, decreases the nValue by one and calls the
function again with the lower nValue
answer = firstTerm * pow(ratio, count);
printf("The value of term %d is: %lf\n", count, answer);
printf("This is the nValue: %d \n", *nValue);
*addedAnswer += answer;
nValue -= 1;
return (goAnswer(nValue, ratio, firstTerm, answer, addedAnswer,
(count + 1)));
}
}

Average of Even Numbers and Product of all Odd Numbers

#include <stdio.h>
#include <conio.h>
int getn(int n, int i);
int main()
{
int n, i;
getn(n, i);
getch();
return 0;
}
int getn(int n, int i)
{
int even = 0;
int odd = 1;
int avg;
printf("Enter ten integers: \n");
for (i = 1 ; i <= 10 ; i++)
{
printf("Integer %d: ", i);
scanf("%d", &n);
if ( n % 2 == 0 )
{
even = even + n;
}
else
{
odd = odd * n;
}
}
avg = even / 10;
printf("\n\nAverage of even numbers: %d", avg);
printf("\nProduct of odd numbers: %d", odd);
}
It seems the even calculations worked but when it comes to odd it gives the wrong answer. Please help
Our instructor wants us to use looping or iterations. No arrays. Please help me
First, your C code needs some correction:
at least give the prototype of getn before using it
getn is defined to return an int and doesn't return anything. Either replace int with void or return a value.
Second,
Your code computes the product of ten numbers, if this product is too big, it cannot be store as-is in an int. For example, it works well if you enter ten times number 3, the result is 59049, but if you enter ten times number 23, it will answer 1551643729 which is wrong because 23^10=41426511213649 but that can't be stored in an int. This is known as arithmetic overflow.
Your average is bad, because you sum ints, but the average is (in general) a rational number (average(2,3)=2.5 isn't it ?). So double avg = out/10.0; (means compute a floating division) and printf("Average %f\n",avg); would be better.

Resources