int main (){
int a, b, sum;
printf("Enter a : ");
scanf("%d", &a);
printf("Enter b : ");
scanf ("%d", &b );
sum= a b;
printf( "Sum of %d and %d = %d",sum );
return 0 ;
}
This is the output I got but it is not correct. Please tell me where I am wrong ?
Enter a: 4
Enter b: 5
Sum of 9 and 6422356 = 4200939
I want to get 'b' (which is the second number) to be printed in the formatted print. but it is not scanning 'b' correctly. Why it is scanning '8' at the place of '4' and '6422356' at the place of '5'? The output should be Sum of 4 and 5 = 9. Tell me what I should do.
When I use printf( "Sum of a and b = %d",sum );
instead of printf( "Sum of %d and %d = %d",sum );
the output is correct
Enter a : 4
Enter b : 5
Sum of a and b = 9
What is the mistake in the previous code? Have I mistaken in the syntax or what? Why %d is not executing properly?
CodePudding user response:
The quantity of variables passed to printf()
does not match the quantity of variables in the format specifier
Three versions to remedy your problem:
// print the NAMES of the variables just entered
printf( "Sum of a and b = %d",sum );
// print the VALUES of the variables just entered
printf( "Sum of %d and %d = %d", a, b, sum );
// or print the NAMES and VALUES of the variables just entered
printf( "Sum of a(%d) and b(%d) = %d", a, b, sum );
You must provide a variable (of the right type) for every "%d" (or other formatting specifier) for printf()
to match-them-up
CodePudding user response:
as you have written 3 %d you need 3 different format specifiers respectively add a and b with sum each sepeated woth comma.. Hope it helps