Why is the number declared in the double function not used? (C) - c

#include <stdio.h>
double calculate_average (int number)
{
static int numberInput = 0; //counter
static int sum = 0;
sum = sum + numberInput;
numberInput++;
return sum / numberInput;
// calculate and return average so far.
}
int main(void)
{
double average;
while (1)
{
int number;
scanf("%d", &number);
if (number == 0)
break; //stops if number == 0
else
average = calculate_average(number);
}
printf("%.1f\n", average);
return 0;
}
As I can personally tell, the function is trying to calculate the average. But why does the main function not use the number in the calculate_average function?

As written, your calculate_average function does not use its given number argument because, nowhere in that function, do you instruct it to do so. Most likely, your sum = sum + numberInput; should really be sum = sum + number; (thus adding that given number to the running total).
A couple of other points:
You should initialize your average variable (to 0.0), otherwise you'll get a crazy result if you give your program an empty list (i.e. give zero as the first entry).
As your function returns a double, it is best to have the sum variable also as a double; otherwise, you are performing integer arithmtic in your calculation, and all returned values will be truncated to integers (losing any fractional parts).
Others will likely point out that you should always check the value returned by your scanf call (it will be 1 if the read operation succeeds) and add code to handle any error; however, addressing that point here is, IMHO, beyond the 'remit' of this question, but see this answer to How validate user input when the expected value is of type int and the entered value is not of type int?.
Here's a possible working version:
#include <stdio.h>
double calculate_average(int number)
{
static int numberInput = 0; //counter
static double sum = 0.0;
sum = sum + number;
numberInput++;
return sum / numberInput;
// calculate and return average so far.
}
int main(void)
{
double average = 0.0; // Always best to initialize variables!
while (1) {
int getal;
scanf("%d", &getal);
if (getal == 0)
break; //stops if getal == 0
else
average = calculate_average(getal);
}
printf("%.1f\n", average);
return 0;
}
Please feel free to ask for any further explanation and/or clarification.

Related

Larger than normal output values?

The program runs but i'm getting some silly values output and i'm not sure why. Could anyone offer some insight?
#include <stdio.h>
int main()
{
// Declare values and open weather.txt
FILE *gpep;
int k;
float wind[11], temp[11], num[11], minT=800, maxT=12, minW=800, maxW=9,
sum_wind=0, sum_temp=0, avgW, avgT;
gpep = fopen("gpep.txt", "r");
if (gpep != NULL){
gpep
for (k = 0; k < 13; k++)
{
fscanf(gpep, "%f %f %f" , &num[k], &wind[k], &temp[k]);
sum_wind += wind[k];
sum_temp += temp[k];
avgW= sum_wind/13;
avgT= sum_temp/13;
printf("Average Temp: %f \n Average wind: %f \n", avgT, avgW);
}
else
{
printf("Can't Open\n" );
}
fclose(gpep);
getchar();
getchar();
return 0;
}
Computation of max and min are wrong, look at this:
if (wind[k] > maxW) {
wind[k]=maxW;
}
it changes your data! Should be like:
if (wind[k] > maxW) {
maxW=wind[k]; // stores a greater value in maxW
}
You also have problems with integer division, consider using doubles:
double avgW; // declare it as a real
and next:
avgW = sum/13.0; // floating division
But, we don't understand why you divide by 13??? Should not be a constant but the current number of read elements:
avgW = ((double)sum)/(k+1); // convert one to double to ensure correct division
---EDIT---
You also have problems with initialization, in fact you don't initialize avg, sum, etc. You must! Initialize them as sum=0, max=less possible value, etc:
int sum=0;
int maxW = INT_MIN;
int minW = INT_MAX;
etc.
I think your problem is because of the integer division (i.e. sum_wind/13 and sum_temp/13). You should declare them as float or double variables in order to get correct division results. Integer division produces the result truncated to zero.

Function to find variance returns 0

I'm working on a program for school that involves finding certain statistics of an array, and one of the things I have to find is the variance, I have a function made for it but for some reason it keeps returning 0
double variance(double * array, unsigned int size, double value)
{
double variance = 0; //Variable used to store the variance
for (unsigned int i = 0; i < size; ++i)
{
if (value > array[i]) //If statement checks to see if you need to subtract the value from the array or the other way around
{
variance += pow((value - array[i]), 2);
}
else
{
variance += pow((array[i] - value), 2);
}
}
variance /= size;
return variance;
}
I've tried going through it with the debugger but I came out with nothing
how I called it:
double varaince = variance(array, size, mean);
printf("\nVariance: %.3lf", variance);
sample output
As #ammoQ commented
double varaince = variance(array, size, mean);
// function name used here.
// printf("\nVariance: %.3lf", variance);
// Use variable name
printf("\nVariance: %.3lf", varaince);
variance/=size;
Should be
variance/=(double)size;
size on its own is stored as a binary integer.

Function to calculate max value of int not returning desired result

I'm just starting out learning C. I'm trying to find the max value of an int by calculation (actually I'm trying to find the max value of a float through the same method, but I want to test it on int first).
The logic seems to be OK, but my function always returns 0 at the end.
int max_int_helper(int base)
{
int prev_i, next_i, counter;
counter = 1;
prev_i = next_i = base + counter;
// found max
if (next_i < base) {
printf("WE RETURN BASE %d\n", base);
return base;
} else {
while(prev_i <= next_i)
{
prev_i = next_i;
counter *= 2;
next_i = base + counter;
}
max_int_helper(prev_i);
}
}
I call it in my main function like this
printf("max int calculated: %d", max_int_helper(0));
But when I run the thing I get this:
WE RETURN BASE 2147483647
max int calculated: 0
I explicitly put the printf statement, so that I'm "sure" I only return once and the value is correct.
Please point me out where it's going wrong.
It is a recursion. You need to return the value of it.
So in the last line it should be:
return max_int_helper(prev_i);

Approximate Pi/Taylor series; prompt user input

I have another problem for homework. This time I know where I am at generally, but I can see that I have some glaring issues with the code. Recently I lost my keys, and it's kind of like that. I don't know exactly WHERE I went wrong with my code, but I have a good idea, and I'd like you to help me find it.
The problem is to approximate pi using the Taylor series.
Now, my problem isn't exactly to get it to approxate so that it equals pi. Rather approximate pi using first N terms as entered by the user. So for example, if I would enter 2, then I should run through the first 2 since N=2. My problem is the way printF represents it (and a variable appears to be uninitialized). Here is my code:
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
//program to calculate series of numbers equal to pi/4
//declare variables
int num_Terms;
int sign= 1;
int n;
float sum= 0.0;
float next_Term;
float final_sum;
//prompt user for input
printf("Enter a value for integer n: ");
scanf("%i",&n);
//perform calculations
for(n = 1; n<= num_Terms; n=n+1) {
sum= sum+next_Term;
next_Term = sign*(1.0/(2*n-1));
sign = sign*-1;
}
final_sum = sum*4;
//display result
printf("\n 4 * %f = %f\n",sum, final_sum);
return 0;
}
I don't know exactly WHERE I went wrong with my code
Firstly you are scanning value into a variable n and then later using it as an iterator variable. Change this to be num_Terms. This should solve your main problem of not considering the number of terms.
Then, it is preferable to initialize the variable before you use it, which would then get rid of the warning you get.
int main(void)
{
//program to calculate series of numbers equal to pi/4
//declare variables
int num_Terms = 0;
int sign = 1;
int n = 0;
float sum = 0;
float next_Term = 0;
float final_sum = 0;
//prompt user for input
printf("Enter a value for integer n: ");
scanf("%i",&num_Terms);
//perform calculations
for(n = 1; n<= num_Terms; n=n+1) {
//not too sure if you need to reverse this order of calculation of sum
sum = sum + next_Term;
next_Term = sign * (1.0/(2*n-1));
sign = sign * -1;
}
final_sum = sum * 4;
//display result
printf("\n 4 * %f = %f\n",sum, final_sum);
return 0;
}

Why am I getting a value of 0 for my min and max?

#include <stdio.h>
#include <stdlib.h>
#include <time.h> /* to initialize your random generator */
#define BUFF_SIZE 10
#define FIVE 5
#define TEN 10
#define ZERO 0
#define ONE 1
float min=0;
float max=0;
float average=0;
float input_buffer[BUFF_SIZE+2] = {0};
float output_buffer[FIVE] = {0};
float local_buffer[TEN];
int no_of_data_pts=0;
int function_id=0;
// a function for generating data size, function ID and
// all data, and putting all of it into input_buffer
void generate_data() {
/* initialize random seed: */
srand ( time(NULL) );
/* Generate a random number: */
input_buffer[0] = floor(1 + 10*(float)rand()/RAND_MAX);
input_buffer[1] = floor(1 + 4*(float)rand()/RAND_MAX);
int i;
for (i=0; i < (int)input_buffer[0]; i++ ){
input_buffer[i+2]=(float)rand()/RAND_MAX;
}
}
// a function for copying the content of input_buffer into
// local buffer (called here my_buffer)
void reading() {
no_of_data_pts= (int)input_buffer[0];
function_id= (int)input_buffer[1];
int i;
for (i=0; i < no_of_data_pts; i++ ){
local_buffer[i]=input_buffer[2+i];
}
}
// a function for processing the content of local buffer;
// it reads function_ID and number of data points from my_buffer
// and saves the results also into my_buffer
void processing() {
float num=0;
int i;
float sum = 0;
float min=0;
for (i=0; i<no_of_data_pts; i++){
num = local_buffer[i+1];
if (num < min) {
min=num;
}
}
for (i=0;i<no_of_data_pts;i++){
num = local_buffer[i+1];
if (num < max) {
max=num;
}
}
for (i=0;i<no_of_data_pts;i++) {
sum = sum + local_buffer[i];
}
average = sum/no_of_data_pts;
}
// a function for copying the content of my_buffer to the
// output_buffer (according to the patter explained earlier)
void writing() {
switch (function_id){
case 1:
output_buffer[0]= min;
printf ("Minimum value is: %f ",output_buffer[0]);
break;
case 2:
output_buffer[0]= max;
printf ("Maximum value is: %f ",output_buffer[0]);
break;
case 3:
output_buffer[0]= average;
printf ("Average value is: %f ",output_buffer[0]);
break;
case 4:
output_buffer[0]= min;
output_buffer[1]= max;
output_buffer[2]= average;
printf ("Minimum, maximum and average value is: %f,%f,%f ",output_buffer[0],output_buffer[1],output_buffer[2]);
break;
}
}
int main () {
setvbuf(stdout, NULL, _IONBF, 0);
setvbuf(stderr, NULL, _IONBF, 0);
generate_data();
reading();
processing();
writing();
return 0;
}
So this is for an C assignment.
So when I run this code, it's supposed to generate some random numbers from 0 to 1 and calculate the min, max and average.
The reading of data from the input buffer involves:
reading a number from the first element of the input buffer, if it is a non-zero number (and it should be), the program performs two following operations, this number represent a number of data points to read (no_of_data_points)
reading ID of a processing function (function_ID)
reading all data points
the ID of data processing function and all points are read into the local buffer
The processing of data involves:
based on read ID of a processing function specific calculations are performed,
four different processing can take place:
if ID is 1: minimum of data points is determined
if ID is 2: maximum of data points is determined
if ID is 3: average of data points is determined
if ID is 4: minimum, maximum and average of data points are determined
the results should be placed into a local buffer.
The writing of data into the output buffer involves:
writing a number indicating how many data points are written into the output
buffer (it includes ID of processing function, and obtained results)
writing a number, called ID of processing function, indicating what operation was
performed on data (range from 1 to 4)
writing the result, and this depends what functions it was:
§ if ID is 1: value of minimum is written
§ if ID is 2: value of maximum is written
§ if ID is 3: value of average is written
§ if ID is 4: values of minimum, maximum and average are written
I then print the results at the very end of the program.
The code runs fine. There are no errors BUT for some reason, I CANNOT figure out why the values of min and max are always 0! My value for average is fine but my max and min values are always 0 for some reason and that's not right.
For starters, this
if (num < max) {
max = num;
}
shall be
if (num > max) {
max = num;
}
at least.
Also using the above approach with initialising min and max to 0 might not work for any kind of input.
To be sure to detect all possiblities of input initialise
min = FLT_MAX;
and
max = -FLT_MAX;
If the smallest/largest possible values are unknown for any reason, change the way how min and max are being detected:
void processing() {
float num=0;
int i;
float sum = 0;
min = local_buffer[1];
for (i = 1; i < no_of_data_pts; i++){
num = local_buffer[i + 1];
if (num < min) {
min = num;
}
}
max = local_buffer[1];
for (i = 1; i < no_of_data_pts; i++){
num = local_buffer[i + 1];
if (num > max) {
max = num;
}
}
...
Also^2 the code defines min twice:
globally
local to processing(), shadowing 1.
Remove the 2nd definition.
The code misses to protoype floor(). That's why the compiler assume it to return an int. This might invoke undefined behaviour.
To fix this add
#include <math.h>
Also^3 when reading out local_buffer in processing() the code use the wrong indexing. The index starts at 0 not at 1. So it is always reading out a last value which had not been set by the generator. That's finally were the 0 for min comes from.
Correcting this would make the above snippet from processing() look like:
void processing() {
float num=0;
int i;
float sum = 0;
min = local_buffer[0];
for (i = 1; i < no_of_data_pts; i++){
num = local_buffer[i];
if (num < min) {
min = num;
}
}
max = local_buffer[0];
for (i = 1; i < no_of_data_pts; i++){
num = local_buffer[i];
if (num > max) {
max = num;
}
}
...
Final notes:
Listen to your compiler, take its warnings serious.
You might like to take into to consideration learning how to use a debugger, to be able to figure such issues on your own the next time.

Resources