Jump to content

Recommended Posts

Posted

a) Write a function, named getNumSum(), for accumulating(summing)float numbers:

->The function has no return value

->The function has 1 input argument named aSum: the current accumulative sum to be "updated" inside this function(Hint: use pass by reference)

->The function asks user for a float input, then updates the accumulative sum

->No code for input validation needed

Posted (edited)

void getNumSum( float &aSum )

{

float data = 0.0;

// ask user for float here...

 

aSum += data;

}

Edited by Sensei
Posted

Thanks but it is not work


You means

 

#include<stdio.h>

void getNumSum( float aSum );
int main()
{
float aSum;
float data = 0.0;
printf("Please input a float number: ");
scanf("%f", &aSum);
aSum += data;
}
Posted (edited)

Rather something like this:

 

#include <stdio.h>

 

void getNumSum( float &aSum ) // do you see difference here?? Parameter must be with &

{

float data = 0.0;

printf("Please input a float number: ");

scanf("%f", &data );

 

aSum += data;

}

 

void main()

{

float aSum = 0.0;

for( int i = 0; i < 5; i++ )

{

getNumSum( aSum );

printf( "Sum %f\n", aSum );

}

}

Edited by Sensei
Posted (edited)

Can't you simply copy and paste to compiler what I wrote in post #4?

This time I have compiled above code, and tested and worked as intended...

Edited by Sensei
Posted

Then your teacher is incompetent..

Because it's in flagrant conflict with this "(Hint: use pass by reference)"...

 

In ANSI C, you have to replace references by pointers.

 

#include <stdio.h>

void getNumSum( float *aSum )
{
float data = 0.0;
printf("Please input a float number: ");
scanf("%f", &data );

*aSum += data;
}

void main()
{
float aSum = 0.0;
for( int i = 0; i < 5; i++ )
{
getNumSum( &aSum );
printf( "Sum %f\n", aSum );
}
}

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.