Jump to content

Need help for C programme


Rocky2013

Recommended Posts

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

Link to comment
Share on other sites

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
Link to comment
Share on other sites

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 );
}
}

Link to comment
Share on other sites

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.