average function returning nan - c

I made this program to order data sets and display the max, min, average, and median. Originally I had everything in main, I decided to clean it up a bit by making functions. The average function was working fund but after adding a few more the value returned for average in 'nan. Any suggestions? Thanks in advance guys
#include <stdio.h>
int findSize();
double findAverage(int size, double num[]);
double findMedian(int size, double num[]);
void findLowtoHigh(int size, double num[]);
void findHightoLow(int size, double num[]);
int main()
{
while(1)
{
int size = findSize();
if(size <= 1)
{
return 0;
}
double num[size];
double holder;
double lowest;
double highest;
double average;
double median;
fprintf(stdout, "\n");
for(int i = 0; i <= size - 1; i++)
{
int j = i+1;
fprintf(stdout, "Please enter number %d: ", j);
fscanf(stdin, "%lf", &num[i]);
}
if(size > 1)
{
for(int y = 0; y < size - 1; y++)
{
for(int k = 0; k < size - 1; k++)
{
if(num[k] > num[k+1])
{
holder = num[k];
num[k] = num[k+1];
num[k+1] = holder;
}
}
}
}
findLowtoHigh(size, num);
findHightoLow(size, num);
average = findAverage(size, num);
median = findMedian(size, num);
fprintf(stdout, "\n\nLowest Value: %3.4f", num[0]);
fprintf(stdout, "\nHighest Value: %3.4f", num[size-1]);
fprintf(stdout, "\n\nAverage Value: %3.4f\n", average);
fprintf(stdout, "Median Value: %3.4f", median);
fprintf(stdout, "\n");
}
}
int findSize()
{
int size;
fprintf(stdout, "\nPlease enter size of the array: ");
scanf("%d", &size);
return size;
}
void findLowtoHigh(int size, double num[])
{
fprintf(stdout, "\nFrom least to greatest: ");
for(int x = 0; x <= size - 1; x++)
{
fprintf(stdout, "%3.2f ", num[x]);
}
}
void findHightoLow(int size, double num[])
{
fprintf(stdout, "\nFrom greatest to least: ");
int reverse = size - 1;
while(reverse != -1)
{
fprintf(stdout, "%3.2f ", num[reverse]);
reverse--;
}
}
double findAverage(int size, double num[])
{
double average;
for(int a = 0; a <= size - 1; a++)
{
average = average + num[a];
}
average = average / size;
return average;
}
double findMedian(int size, double num[])
{
double median;
if(size % 2 == 0)
{
median = (num[size/2 - 1] + num[size/2])/2;
}
else
{
median = num[size/2];
}
return median;
}

You have to initialize average. Change to
double average=0;

Compile your prrogram with (mild) optimization and all reasobnable warnings turned on (gcc -O -Wall is a starting point on Linux, clang is similar), and check (and fix!) all complaints by the compiler. Only then are you allowed to ask the 'net.

Related

"assignment makes integer from pointer without a cast"?

I'm really new to this. I've never done anything like this so I'm having issues with this code. I was given a template to write my code in separate functions like this, although I added the findPos one myself. I'm getting the "assignment makes integer from pointer without a cast" warning and also my max, min, sum, avg, and position of max and min are obviously not coming out to the right numbers. I was just wondering if anyone can lead me in the right direction.
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int findMin(int arr[], int size);
int findMax(int arr[], int size);
int findSum(int arr[], int size);
int findPos(int arr[], int size);
int size;
int i;
int max;
int min;
int avg;
int sum;
int pos;
int main()
{
srand(time(0));
printf("Enter an integer: ");
scanf("%d", &size);
int arr[size];
max = findMax;
min = findMin;
pos = findPos;
sum = findSum;
avg = sum / size;
printf("max:%7d\tpos:%d\t\n", max, pos);
printf("min:%7d\tpos:%d\t\n", min, pos);
printf("avg:%7d\n", avg);
printf("sum:%7d\n", sum);
printf("\n");
printf(" Pos : Val\n");
printf("-------------\n");
for (i = 0; i < size; i++) {
arr[i] = (rand() % 1001);
printf("%4d :%6d\n", i, arr[i]);
}
return 0;
}
int findMin(int arr[], int size)
{
min = arr[0];
for (i = 0; i < size; i++) {
if (arr[i] < min) {
min = arr[i];
}
}
return min;
}
int findMax(int arr[], int size)
{
max = arr[0];
for (i = 0; i < size; i++) {
if (arr[i] > max) {
max = arr[i];
}
}
return max;
}
int findSum(int arr[], int size)
{
sum = 0;
for (i = 0; i < size; i++) {
sum = sum + arr[i];
}
return sum;
}
int findPos(int arr[], int size)
{
for (i = 0; i < size; i++) {
pos = i;
}
return pos;
}
max = findMax;
min = findMin;
pos = findPos;
sum = findSum;
You're assigning function pointer, not return value, to integer variable. You have to do something like max = findMax(arr, size). Also in that case, you should assign values to arr before calling it.
There are a couple of issues with the code. Let me iterate through the same
Populating Data in Created Array
Since the data has to present the created array before performing any operations,
printf("\n");
printf(" Pos : Val\n");
printf("-------------\n");
for (i = 0; i < size; i++) {
arr[i] = (rand() % 1001);
printf("%4d :%6d\n", i, arr[i]);
}
this snippet should be reordered and moved above the function calls and just after the int arr[size];
Function Calls
All your functions, namely findMax,findMin,findPos,findSum is expecting two parameters
arr - array you have created
size - the size value read from scanf()
Assuming you want to store the return value from the function in the main int variables max,min,pos,sum,avg
the statements
max = findMax;
min = findMin;
pos = findPos;
sum = findSum;
should be replaced with function calls like
max = findMax(arr, size);
min = findMin(arr, size);
pos = findPos(arr, size);
sum = findSum(arr, size);
The Final Main code will be
int main()
{
srand(time(0));
printf("Enter an integer: ");
scanf("%d", &size);
int arr[size];
printf("\n");
printf(" Pos : Val\n");
printf("-------------\n");
for (i = 0; i < size; i++) {
arr[i] = (rand() % 1001);
printf("%4d :%6d\n", i, arr[i]);
}
max = findMax(arr, size);
min = findMin(arr, size);
pos = findPos(arr, size);
sum = findSum(arr, size);
avg = sum / size;
printf("max:%7d\tpos:%d\t\n", max, pos);
printf("min:%7d\tpos:%d\t\n", min, pos);
printf("avg:%7d\n", avg);
printf("sum:%7d\n", sum);
return 0;
}

How can I pass values from one function to another?

I have created a program that takes in input "n" numbers that the user chooses and then prints the most repeated one, but I have a problem with passing the values between the functions so it gives me 0 as a result. How can I solve it?
void most_present_number(int array[]);
int read_numbers(int array[]);
int main() {
int array[400];
most_present_number(array);
return 0;
}
void most_present_number(int array[]){
read_numbers(array);
int i = 0;
int Max = 0;
int Current_number = vettore[0];
int Current_number_counter = 0;
int most_present_number = 0;
int most_present_number_counter = 0;
while (i < Max) {
if (array[i] == Current_number) {
Current_number_counter++;
i++;
} else {
if (Current_number_counter > most_present_number_counter){
most_present_number = Current_number;
most_present_number_counter = Current_number_counter;
}
Current_number = array[i];
Current_number_counter = 1;
i++;
}
}
printf("The most present number is %d which is repeated %d times\n", most_present_number,
most_present_number_counter);
}
int read_numbers(int array[]){
int Max = 0;
int i = 0;
printf("Insert the array lenght\n");
scanf("%d", &Max);
while (i < Max) {
printf("Insert the numbers\n");
scanf("%d", &array[i]);
i++;
}
return Max;
}
You have Max = 0 in most_present_number(), so the while loop stops immediately.
read_numbers() returns Max, so you can use this to initialize Max in most_present_number().
void most_present_number(int array[], int Max);
int read_numbers(int array[]);
int main() {
int array[400];
int size;
most_present_number(array);
return 0;
}
void most_present_number(int array[]){
int Max = read_numbers(array);
int i;
int Current_number = array[0];
int Current_number_counter = 0;
int most_present_number = 0;
int most_present_number_counter = 0;
for (i = 0; i < Max; i++) {
if (array[i] == Current_number) {
Current_number_counter++;
} else {
if (Current_number_counter > most_present_number_counter){
most_present_number = Current_number;
most_present_number_counter = Current_number_counter;
}
Current_number = array[i];
Current_number_counter = 1;
}
}
printf("The most present number is %d which is repeated %d times\n", most_present_number,
most_present_number_counter);
}
int read_numbers(int array[]){
int Max = 0;
int i = 0;
printf("Insert the array lenght\n");
scanf("%d", &Max);
while (i < Max) {
printf("Insert the numbers\n");
scanf("%d", &array[i]);
i++;
}
return Max;
}
Note also that your algorithm assumes that all the equal numbers will be together in the array. If they can be mixed up, you need a very different design. You need another array where you keep the counts of each number. Then at the end you find the entry in this array with the highest count.

How to pass arrays to functions

I am trying to write a program which calculates some bags and weights. I wrote it without using functions but I have to use functions and I am really bad at it.
The code normally works, but I just can't implement it with functions. It stops working after printing array A, and just 0s when printing array B.
My code is:
#include <stdio.h>
#include <math.h>
int f1(int N);
int f2(int N);
int f3(int N, float A[20]);
int main(void)
{
int N;
f1(N);
return 0;
}
int f1(int N)
{
for(;;)
{
printf("Enter N(the number of bags) (Between 1 and 20): ");
scanf("%d", &N);
if (N < 1 || N > 20)
{
continue;
}
else
{
break;
}
}
f2(N);
}
int f2(int N)
{
float A[20];
int i;
for(i=0; i<N;i++)
{
printf("Enter the weight of the bag with potatoes %d: ", i+1);
scanf("%f", &A[i]);
}
printf("\n\nThe weights of the initial bags (the A array):\n");
for(i=0; i<N;i++)
{
printf("%.1f " ,A[i]);
}
f3(N, &A[20]);
}
int f3(int N, float A[20])
{
int i;
float B[10];
printf("\n\nNow we equalize the weights of bags.\n");
if (N%2 == 0)
{
for(i=0;i<N/2 ;i++)
{
B[i] = fabsf(A[i] - A[N-1-i]);
}
}
else
{
for(i=0;i<N/2 ;i++)
{
B[i] = fabsf(A[i] - A[N-1-i]);
}
B[N/2] = A[N/2];
}
if (N%2 == 0)
{
for (i=0; i<N/2; i++)
{
if (A[i] < A[N-1-i])
{
A[N-1-i] = A[i];
}
else
{
A[i] = A[N-1-i];
}
}
}
else
{
for (i=0; i<N/2; i++)
{
if (A[i] < A[N-1-i])
{
A[N-1-i] = A[i];
}
else
{
A[i] = A[N-1-i];
}
}
A[N/2] = 0;
}
printf("\nThe weights of the new bags (the B array):\n");
if (N%2 == 0)
{
for(i=0; i<N/2 ;i++)
{
printf("%.1f " ,B[i]);
}
}
else
{
for(i=0; i<N/2 ;i++)
{
printf("%.1f " ,B[i]);
}
printf("%.1f", B[N/2]);
}
printf("\nThe new weights of the initial bags (the A array):\n");
for(i=0;i<N;i++)
{
printf("%.1f ", A[i]);
}
}
To pass an array to a function just use its name.
f3(N, &A[20]);
should be
f3(N, A);
To pass an array or pointer as an argument when calling a function in C, you just need to pass it name, in your case,
f3(N, A);
Also, when declaring the function, the length of the array doesn't matter, because C performs no bounds checking for formal parameters. Although it will work this way, it is best to change
int f3(int N, float A[20])
to
int f3(int N, float A[])
or
int f3(int N, float* A)

how to return two values in one function without using struct?

#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,&gtr);
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, &gtr);
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.

For/while loop doesn't update value properly

I'm trying to write a program which finds the weighted average (for grades and such).
Through user input, I create two arrays of the same size, one carrying the weights for each grading category, and the other holding the users score in the corressponding category. For example, if a student has a score of 92% in category 1, which is worth 30% of the total grade, then weights[1] = .3 and scores[1] = .92. This way, the average in each category can be found through (weights[i] * scores[i]) where i is an instance variable initialized in a for loop to go through each array entirely. The problem here is in finding the cumulative average- my program is written to compound the values of each average it handles for example I have tried code like average = average + (weights[i] * scores[i]) to obtain the final cumulative average. However through print statements I've found the value of average is set to the last (weights[i] * scores[i]) operation performed, ignoring the previous value of average (or taking it to be 0). For example, if weights[]={.3, .3, .4} and scores[] = {.4, .4 , .4}. The cumulative average should be .4, but my program tells me .32, which is the last value of weights times the last value of scores.
methods.c:
#include <stdio.h>
#include "methods.h"
int howManyCategories()
{
int categories = 0;
int firstTime = 0;
while(1)
{
if(firstTime == 0)
{
fprintf(stdout, "\nHow many categories are you currently graded on? ");
scanf("%d", &categories);
}
else
{
fprintf(stdout, "\nThat's not a valid value, try a positive integer. ");
scanf("%d", &categories);
}
firstTime++;
if(categories > 0)
{
return categories;
}
}
}
double howMuchWeight(int categories)
{
double weight = 0;
while(1)
{
if(categories == 1)
{
fprintf(stdout,
"\nThis %d category accounts for how much of your grade? (.1, .85, 1 etc.) ",
categories);
scanf("%lf", &weight);
}
else
{
fprintf(stdout,
"\nThese %d categories account for how much of your grade? (.1, .85, 1 etc.) ",
categories);
scanf("%lf", &weight);
}
if(weight > 1 || weight <= 0)
{
fprintf(stdout,
"\nRemember, total weighting must be positive and no larger than 1"
" (100 percent). \nTry Again.\n");
}
else
{
return weight;
}
}
}
double findWeightsAndScores(int i, double categories,
double checkWeights, double totalWeight,
double scores[])
{
while(1)
{
double piece = 0;
int count = i + 1;
fprintf(stdout, "\nWeight for category %d: ", count);
scanf("%lf",&piece);
if(piece > 0 && piece < 1)
{
findScores(i, &scores[i]);
return piece;
}
else
{
fprintf(stdout, "\nRemember, weights must be positive and less than 1!\n");
}
}
}
void findScores(int i, double scores[])
{
int validScore = 0;
while(validScore == 0)
{
int count = i + 1;
double score = 0;
fprintf(stdout, "Please enter your percentage score in category %d: ", count);
scanf("%lf", &score);
if(score >= 0 && score <= 1)
{
scores[i] = score;
validScore = 1;
}
else
{
fprintf(stdout, "\nRemember, scores in each category must be positive, no greater "
"than 1 (100 percent) and no less than 0, try again.\n\n");
}
}
}
double findAverage(int categories, double weights[], double scores[])
{
double average = 0;
for(int i = 0; i <= categories - 1; i++)
{
average += (weights[i] * scores[i]);
fprintf(stdout, "%lf", average);
}
return average;
}
methods.h:
#ifndef METHODS_H_
#define METHODS_H_
int howManyCategories();
double howMuchWeight(int categories);
double findWeightsAndScores(int i, double categories,
double checkWeights, double totalWeight, double scores[]);
void findScores(int i, double scores[]);
double findAverage(int categories, double weights[], double scores[]);
#endif
whatsmyGrade.c:
#include <stdio.h>
#include "methods.h"
int main()
{
while(1)
{
/*Prompts for categories*/
int categories = howManyCategories();
int dataProvided = 1;
double checkWeights = 0;
double grade = 0;
double average = 0;
/*Prompts for total weight*/
double totalWeight = howMuchWeight(categories);
double category[categories];
double weights[categories];
double scores[categories];
/*Assign weights to each category and score in each category*/
for(int i = 0; i <= categories - 1; i++)
{
/*Fill array for weights*/
weights[i] = findWeightsAndScores(i, categories, checkWeights, totalWeight,
scores);
checkWeights = checkWeights + weights[i];
if(checkWeights != totalWeight && i == categories - 1)
{
fprintf(stdout, "\nYour weight distribution is invalid! Try again.\n");
dataProvided = 0;
break;
}
}
/*Calculate total grade*/
if(dataProvided == 1)
{
average = findAverage(categories, weights, scores);
grade = (average / totalWeight) * 100;
fprintf(stdout, "Your cumulative average is %.2lf percent\n\n", grade);
return 1;
}
}/*End of parent while loop*/
}/*End of main*/
Thank you in advance
Your problem is somewhere else because it works like a charm for me:
#include <stdio.h>
double findAverage(int categories, double weights[], double scores[])
{
double average = 0;
int i;
for(i = 0; i <= categories - 1; i++) {
average += (weights[i] * scores[i]);
fprintf(stdout, "%lf ", average);
}
return average;
}
int main(void) {
// your code goes here
double average;
double grade;
int categories = 3;
double totalWeight = .3 + .3 + .4;
double weights[] = {.3, .3, .4};
double scores[] = {.4, .4, .4};
average = findAverage(categories, weights, scores);
grade = (average / totalWeight) * 100;
fprintf(stdout, "\nYour cumulative average is %.2lf percent\n\n", grade);
return 0;
}
Got it, when I call the findScores function in the findWeightsAndScores function I was passing it &scores[i] when I should have been passing it scores. Thanks guys

Resources