SBK SBK - 2 months ago 12
C Question

Bug in simple C source code?

I want to know if the format of user defined function i wrote i.e return(xxx) is correct or not .
Because when i compile my code, i have to enter the input 2 times.It might be a silly mistake because i just began learning C language
****MY CODE:****``

#include<stdio.h>
long cube(long x );
long input,answer;
int main (void )
{
printf("Enter a number:");
scanf("%ld ",&input);
answer = cube(input);
printf(" The cube of %ld is %ld",input ,answer);
return 0;
}
long cube(long x )
{
return (x*x*x);
}


****ANswer****

#include <stdio.h>
long cube(long x);
long input, answer;
int main( void )
{
printf("Enter an integer value: ");
scanf("%d", &input);
answer = cube(input);
printf("\nThe cube of %ld is %ld.\n", input, answer);
return 0;
}


long cube(long x)
{
long x_cubed;

x_cubed = x * x * x;
return x_cubed;
}

Answer Source

remove the space after '%ld' it will take one input. according your code, scanf("%ld '&input) ; here compiler at first wants one input for '%ld' then it waits for blank space you used after '%ld'. remove it then it will go next step after one input. you should use, scanf("%ld%",&input);