Jump to content

Need help for C programme

Featured Replies

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

void getNumSum( float &aSum )

{

float data = 0.0;

// ask user for float here...

 

aSum += data;

}

Edited by Sensei

  • Author

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

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

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

It's not exactly what I posted in #4. Compare lines one by one..

References are in cpp, not in old c.

Rename file and should be fine.

Edited by Sensei

  • Author

Teacher ask me finishing this lab in c programme so could you teach me how to achieve the above target in c programme, Pleasesad.png

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

Mine code is for loop 5 times, not 3.

And text displayed to user is different.

fSum instead of aSum as name.

Archived

This topic is now archived and is closed to further replies.

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.

Configure browser push notifications

Chrome (Android)
  1. Tap the lock icon next to the address bar.
  2. Tap Permissions → Notifications.
  3. Adjust your preference.
Chrome (Desktop)
  1. Click the padlock icon in the address bar.
  2. Select Site settings.
  3. Find Notifications and adjust your preference.