#include <stdio.h>
float aver(float*,int);
float max = 0, min = 0; // define global variables
int main()
{
int i;
float num[10]; //input number
for (i = 0 ; i < 10 ; i++)
scanf("%f", &num[i]);
printf("%.2f %.2f %.2f ", max, min, aver(num, i)); //output max ,min and aver
return 0;
}
float aver(float*num,int n)
{
max = min = num[0];
int i;
float sum=0;
for (i=0; i<n-1; i++) {
if (max < num[i])
max = num[i]; //find max
else if (min > num[i])
min = num[i]; //find min
sum += num[i];
}
printf("%.2f %.2f \n ",max,min); //output the max and the min in the array num
return sum/n;
}
Is is what i input and get.
1 2 3 4 5 6 7 8 9 10
9.00 1.00
0.00 0.00 4.50 Program ended with exit code: 0
Why the max and the min in the function aver can output correctly, but in the main function they are 0?
Order of evaluation of function arguments is unspecified. So your code may work as expected on some compilers while may give unexpected results on other compilers.
You should replace
printf("%.2f %.2f %.2f ",max,min,aver(num, i)); //output max ,min and aver
with
{
float average = aver(num, i);
printf("%.2f %.2f %.2f ",max,min, average); //output max ,min and aver
}
to make the code behavior well defined.
from C99 ยง6.5.2.2p10:
The order of evaluation of the function designator, the actual
arguments, and subexpressions within the actual arguments is
unspecified, but there is a sequence point before the actual call.
The order of evaluation of the arguments of printf is unspecified,i.e,max and min can be printed after or before evaluating aver function. In your case,aver is called after printing max and min and then, this function modifies the max and min variables.
To fix it, just call aver as an argument in another printf
Related
I am writing a code which requires me to use the malloc function, feed input into an array, determine and print the average as well as how each array value relates to the average. Here is my code
#include <stdio.h>
#include <stdlib.h>
int main (){
int i, n;
float* numbers;
float sum, average;
sum = 0;
printf("How many numbers? ");
scanf("%d", &n);
numbers = (int*)malloc(n * sizeof(int));
printf("Enter %d decimal numbers\n", n);
for(i = 0; i < n; i++)
{
scanf("%f", &numbers[i]);
printf("%f\n", &numbers[i]);
sum = sum + numbers[i];
}
printf("%f\n", &sum);
average = sum / n;
printf("The average was %f\n", &average);
for(i = 0; i < n; i++)
{
if (numbers[i] < average)
printf("%f is less than the average\n" , &average);
else if (numbers[i] > average)
printf("%f is less than the average\n" , &average);
else
printf("%f is average\n" , &average);
}
return 0;
}
The print statement in the very first for loop I was using to check whether or not my array is receiving the input properly, it is not, as shown by my output, which is below, my question is why is my array not receiving the values?
How many numbers? 4
Enter 4 decimal numbers
4
0.000000
4
0.000000
4
0.000000
4
0.000000
0.000000
The average was 0.000000
0.000000 is average
0.000000 is average
0.000000 is average
0.000000 is average
A few corrected issues:
1)
numbers = (int*)malloc(n * sizeof(int));
Allocation of memory for int was replaced with the allocation for float.
Cast is not required.
numbers = malloc(n * sizeof(float));
2)
printf("%f\n", &numbers[i]);
The intention is not to print a pointer to number[i] but the number[i] itself.
printf("%f\n", numbers[i]);
This type of issue was corrected for a few other printing places.
3) Final prints was corrected, logically program required printing the numbers[i] not the average
if (numbers[i] < average)
printf("%f is less than the average\n" , numbers[i] );
else if (numbers[i] > average)
printf("%f is more than the average\n" , numbers[i] );
Corrected program:
#include <stdio.h>
#include <stdlib.h>
int main (){
int i,n;
float* numbers;
float sum, average;
sum = 0;
printf("How many numbers? ");
scanf("%d", &n);
numbers = malloc(n * sizeof(float));
printf("Enter %d decimal numbers:\n", n);
for(i = 0; i < n; i++)
{
scanf("%f", &numbers[i]);
printf("%f\n", numbers[i]);
sum = sum + numbers[i];
}
printf("%f\n", sum);
average = sum / n;
printf("The average was %f\n", average);
for(i = 0; i < n; i++)
{
if (numbers[i] < average)
printf("%f is less than the average\n" , numbers[i] );
else if (numbers[i] > average)
printf("%f is more than the average\n" , numbers[i] );
else
printf("%f is average\n" , average);
}
return 0;
}
OUTPUT:
How many numbers? Enter 4 decimal numbers:
2
10
5
8
2.000000
10.000000
5.000000
8.000000
25.000000
The average was 6.250000
2.000000 is less than the average
10.000000 is more than the average
5.000000 is less than the average
8.000000 is more than the average
The problem is here:
printf("%f\n", &numbers[i]);
You're printing a reference to numbers[i] instead of the value itself. Try:
printf("%f\n", numbers[i]);
Same thing for all the other places you print values (i.e. sum, average). You're getting 0's when you print it because when you take a pointer to one of those values and cast it to a float it is interpreting that as zero.
Perhaps someone else will be able to enlighten us an exactly why that is (i.e. I'm not sure if that is undefined behavior).
In case you're still confused: the reason you have to pass a reference (&) to the value to scanf, yet the value itself to printf, here's the reason: for scanf you're telling it "please get a float from the console and put it at this location I am specifying (i.e &numbers[i])". When you call printf, you are telling it "please print this value I am giving you (i.e. numbers[i])".
sum=0f;
Writing f so that it is interpreted as float constant instead of double.This doesn't matter much but is good practice and can help striking out a lot of problems.
numbers = (float*)malloc(n * sizeof(float));
Since you want a float array and not an integer array.
printf("%f\n",numbers[i]);
Use '&' only when you want to access the address of variable . To access the value stored in the variable simply use the variable name.
printf("Sum is : %f\n", sum);
Writing proper message in output is important.
for(i = 0; i < n; i++) { if (numbers[i] < average) printf("%f is less than the average\n" , numbers[i]); else if (numbers[i] > average) printf("%f is less than the average\n" , numbers[i]); else printf("%f is average\n" , numbers[i]); }
You need to print the value of number[i] instead of average.
And remember not to use & in printf unless you want to print a address
First fix the malloc
numbers = malloc(n * sizeof(float)); // Not 'int'
then fix the for and next printf
printf("%f\n", numbers[i]); // printf wants a value not an address
printf("%f\n", sum); // same
then
printf("The average was %f\n", average); // same
and the 3 next similar printf.
disclaimer: I'm new to programming
I'm working on this problem
so far ive written this which takes user inputs and calculates an average based on them
#include <stdio.h>
int main()
{
int n, i;
float num[100], sum = 0.0, average;
for(i = 0; i < n; ++i)
{
printf("%d. Enter number: ", i+1);
scanf("%f", &num[i]);
sum += num[i];
}
average = sum / n;
printf("Average = %.2f", average);
return 0;
}
I'd like the user to enter -1 to indicate that they are done entering data; I can't figure out how to do that. so if possible can someone explain or give me an idea as to how to do it
Thank you!
#include <stdio.h>
int main()
{
int i = 0;
float num[100], sum = 0.0, average;
float x = 0.0;
while(1) {
printf("%d. Enter number: ", i+1);
scanf("%f", &x);
if(x == -1)
break;
num[i] = x;
sum += num[i];
i++;
}
average = sum / i;
printf("\n Average = %.2f", average);
return 0;
}
There is no need for the array num[] if you don't want the data to be used later.
Hope this will help.!!
You just need the average. No need to store all the entered numbers for that.
You just need the number inputs before the -1 stored in a variable, say count which is incremented upon each iteration of the loop and a variable like sum to hold the sum of all numbers entered so far.
In your program, you have not initialised n before using it. n has only garbage whose value in indeterminate.
You don't even need the average variable for that. You can just print out sum/count while printing the average.
Do
int count=0;
float num, sum = 0;
while(scanf("%f", &num)==1 && num!=-1)
{
count++;
sum += num;
}
to stop reading at -1.
There is no need to declare an array to store entered numbers. All you need is to check whether next entered number is equal to -1 and if not then to add it to the sum.
Pay attention to that according to the assignment the user has to enter integer numbers. The average can be calculated as an integer number or as a float number.
The program can look the following way
#include <stdio.h>
int main( void )
{
unsigned int n = 0;
unsigned long long int sum = 0;
printf("Enter a sequence of positive numbers (-1 - exit): ");
for (unsigned int num; scanf("%u", &num) == 1 && num != -1; )
{
++n;
sum += num;
}
if (n)
{
printf("\nAverage = %llu\n", sum / n);
}
else
{
puts("You did not eneter a number. Try next time.");
}
return 0;
}
The program output might look like
Enter a sequence of positive numbers (-1 - exit): 1 2 3 4 5 6 7 8 9 10 -1
Average = 5
If you need to calculate the average as a float number then just declare the variable sum as having the type double and use the corresponding format specifier in the printf statement to output the average.
this code just generates a random number to be taken in as the temperature and records it every hour. I am having issues with my for loop on getting the max and min values of my code. It looks correct to me and similar to all the examples I have seen but it's giving me the wrong output.
Thank you
#include <stdio.h>
#include <stdlib.h>
void GetValue(int[], int x);
#define array_size 25
int main() {
int x, max, min, temperature[25];
float sum;
float average;
int array[array_size];
printf("Temperature Conditions on October 9, 2015:\n");
printf("Time of Day \t Temperature in Degrees F\n");
for (x = 0; x < 25; x++) {
//if statements to get min and max
GetValue(temperature, x);
if (temperature[x] > max) {
max = temperature[x];
}
if (temperature[x] < min) {
min = temperature[x];
}
printf("%d \t \t \t %d\n", x,temperature[x]);
}
//prints statements
printf("\nMaximum Temperature for the day: %d Degrees F\nMinimum Temperature for the day: %d Degrees F\n", temperature[12],max, min);
//adds up all temps
sum=0;
for (x=0;x<25;x++){
sum=(sum+temperature[x]);
}
//prints and creates average
average=sum/25;
printf("Average Temperature for the day: %.2f Degrees F\n",average);
return 0;
}
//gets values and puts them into array
void GetValue(int value[], int x) {
value[x] = (rand()%(100-60+1))+60;
}
You invoked undefine behavior by using values of uninitialized variables having automatic storage duration, which is indeterminate.
Use values of variables only after assigning some value to them.
Format your code properly.
Match format specifier and data for printf().
Avoid using magic number. Use the #defined number for number of elements in this case.
Corrected code:
#include <stdio.h>
#include <stdlib.h>
void GetValue(int[], int x);
#define array_size 25
int main(void) {
int x, max = 0, min = 0, temperature[array_size];
float sum;
float average;
printf("Temperature Conditions on October 9, 2015:\n");
printf("Time of Day \t Temperature in Degrees F\n");
for (x = 0; x < array_size; x++) {
//if statements to get min and max
GetValue(temperature, x);
// in the first iteration, there won't be a valid number in max and min
if (x == 0 || temperature[x] > max) {
max = temperature[x];
}
if (x == 0 || temperature[x] < min) {
min = temperature[x];
}
printf("%d \t \t \t %d\n", x, temperature[x]);
}
//prints statements
printf("\nMaximum Temperature for the day: %d Degrees F\nMinimum Temperature for the day: %d Degrees F\n", max, min);
//adds up all temps
sum=0;
for (x=0;x<array_size;x++){
sum=(sum+temperature[x]);
}
//prints and creates average
average=sum/array_size;
printf("Average Temperature for the day: %.2f Degrees F\n", average);
return 0;
}
//gets values and puts them into array
void GetValue(int value[], int x) {
value[x] = (rand()%(100-60+1))+60;
}
So I'm making a ghetto weather report by creating a random number generator anywhere from 60-100 and storing 25 of these in an array. Then I have a function that calculates max, min, and average along with printing all of this out.
I got it to run without error, but all I'm getting are a bunch of zeros in my display, which means I'm messing up big time somewhere in the calculation, any suggestions?
Also I'm trying to get down calling user-defined functions which is why I have several.
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int sum = 0;
int min = 0;
int max = 0;
int temp[25];
int i = 0;
float avg = 0;
int main () {
srand( (unsigned) time(NULL) );
for (i=0; i < 25; i++) {
get_value(i);
sum += temp[i];
}
calc_results(temp[25]);
return 0;
};
int get_value(void) {
return((rand() % (100 - 60 + 1)) + 60);
};
int calc_results(int temp_number[], int number) {
avg = ((sum)/(25));
max = temp[0];
for(i=1;i<25;i++){
if(max<temp[i])
max=temp[i];
};
min =temp[0];
for(i=1;i<25;i++){
if(min>temp[i])
min=temp[i];
};
printf("Temperature Conditions on October 9, 2015 : \n");
printf("Time of day Temperature in degrees F \n");
printf(" 0 %d\n",temp[0]);
printf(" 1 %d\n",temp[1]);
printf(" 2 %d\n",temp[2]);
printf(" 3 %d\n",temp[3]);
printf(" 4 %d\n",temp[4]);
printf(" 5 %d\n",temp[5]);
printf(" 6 %d\n",temp[6]);
printf(" 7 %d\n",temp[7]);
printf(" 8 %d\n",temp[8]);
printf(" 9 %d\n",temp[9]);
printf(" 10 %d\n",temp[10]);
printf(" 11 %d\n",temp[11]);
printf(" 12 %d\n",temp[12]);
printf(" 13 %d\n",temp[13]);
printf(" 14 %d\n",temp[14]);
printf(" 15 %d\n",temp[15]);
printf(" 16 %d\n",temp[16]);
printf(" 17 %d\n",temp[17]);
printf(" 18 %d\n",temp[18]);
printf(" 19 %d\n",temp[19]);
printf(" 20 %d\n",temp[20]);
printf(" 21 %d\n",temp[21]);
printf(" 22 %d\n",temp[22]);
printf(" 23 %d\n",temp[23]);
printf(" 24 %d\n",temp[24]);
printf(" 25 %d\n",temp[25]);
printf("Maximum Temperature for the day: %d Degrees F\n", max);
printf("Minimum Temperature for the day: %d Degrees F\n", min);
printf("Average Temperature for the day: %.1f Degrees F\n", avg);
};
firstly dude use loop to print 25 printf statements... ur code would be a bit smaller...
do the following changes and it should work pretty okay...
time_t t;
srand((unsigned) time(&t)); // this is a more standard way of using srand
also you have passed and int in get_value() whose parameter is void...
do this in the for loop in main
temp[i]=get_value();
also declare your functions on above of your code...
you dont need calc_results() like this...
do it
void calc_results(void)
and no neeed of passing temp since its already global...no need of passing number type integer since you are not using any such thing...no need of using return type as int since you dont need to return any integer...
final suggestion... Get a good book on functions
so your final code would look something like this:-
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int get_value(void);
void calc_results(void);
int sum = 0;
int min = 0;
int max = 0;
int temp[25];
int i = 0;
float avg = 0;
int main () {
time_t t;
srand((unsigned) time(&t));
for (i=0; i < 25; i++) {
temp[i]=get_value();
sum += temp[i];
}
calc_results();
return 0;
};
int get_value(void) {
return((rand() % (100 - 60 + 1)) + 60);
};
void calc_results(void) {
avg = ((sum)/(25));
max = temp[0];
for(i=1;i<25;i++){
if(max<temp[i])
max=temp[i];
};
min =temp[0];
for(i=1;i<25;i++){
if(min>temp[i])
min=temp[i];
};
printf("Temperature Conditions on October 9, 2015 : \n");
printf("Time of day Temperature in degrees F \n");
for(int j=0;j<25;j++){
printf(" %d %d\n",i,temp[i]);
}
printf("Maximum Temperature for the day: %d Degrees F\n", max);
printf("Minimum Temperature for the day: %d Degrees F\n", min);
printf("Average Temperature for the day: %.1f Degrees F\n", avg);
};
also Dont use global variables unless local variables fail...this would be at great help when you do some big codes and file handling
Just chance this line
get_value(i);
To
temp[i]=get_value(i);
Because you have to store the random values in temp[i] then you can calculate the other values.
And while you passing the array. You should do this--
calc_results(temp);
You can print all array value by a for loop. Like this:
int cnt;
for(cnt = 0; cnt<=25; cnt++)
{
printf(" %d %d\n",cnt,temp[cnt]);
}
You aren't assigning temp[i] any value?
for (i=0; i < 25; i++) {
temp[i] = get_value(i);
sum += temp[i];
}
This program gets 5 numbers only from the user then
Store them in an array. Get the min, max, and the average of the numbers inputted. Here's the code I made:
#include <stdio.h>
#include <conio.h>
int main()
{
int num[5];
int min, max=0;
int counter;
float average, total;
max = num[0];
min = num[2];
for(counter=0; counter<=4; counter++)
{
printf("Enter a number: ");
scanf("%d", &num[counter]);
if(num[counter]>max)
{
max = num[counter];
}
if (num[counter]<min)
{
min = num[counter];
}
}
total = max+min;
average = total/2;
printf("The maximum number is: %d\n", max);
printf("The minimum number is: %d\n", min);
printf("The average is: %d", average);
getch();
return 0;
}
FInally fixed my error with the min and max and now I'm having trouble with the average. I should only get the average of the min and max numbers but it keeps on showing an average of zero. Can someone help? Thankkyouuu.
//get memory address and store value in it.
void getValue(int *ptr)
{
printf("Enter a number: ");
scanf("%d", ptr);
}
int main()
{
//initialized n=5 as per your requirement. You can even get the value at run time.
int min, max, counter,n=5;
int num[n];
float average,total;
getValue(num); //get num[0]
min=max=total=num[0]; //Initialize min,max,total with num[0]
for(counter=1; counter<n; counter++)
{
getValue(num+counter); //get num[counter]
num[counter]>max?max = num[counter]:max; //find max
num[counter]<min?min = num[counter]:min; //find min
total+=num[counter]; // total = total + num[counter]
}
average = total/n;
printf("The maximum number is: %d\n", max);
printf("The minimum number is: %d\n", min);
printf("The total is: %f\n", total);
printf("The average is: %f\n", average);
return 0;
}
Your calculation of average is wrong; you need to use total/num (remember use float):
total += num[counter];
max and min were incorrectly initialized: num[0], num[2] may be anything when you initialize them.
Aside from your calculation of average being wrong (it's not just total/2), you need to use the correct format specifier in the printf:
printf("The average is: %g", average);
You are using %d which tells printf to expect an integer, but you're giving it a float.
1 Min and max should be initialized
int min = INT_MAX;
int max = INT_MIN;
2 You need to keep a running total of your numbers
int total = 0;
...
// inside loop
scanf("%d", &num[counter]);
total += num[counter];
3 At the end print the average, recommend going to floating point.
printf("The average is: %.1f", (double)total/counter);