Why my program is giving garbage value in O/P after providing sufficient inputs?
I have given I/P as 10 & 40
& choose multiplication option as 3
.
My code is as follows:
int main()
{
int a,b,c,x;
printf("Enter a & b \n"); //printing
scanf("%d %d, &a,&b");
printf("1. add \n 2. sub \n 3. multiply \n 4. div \n 5. mod \n 6. and \n 7. or\n 8. not \n 9. xor \n");
printf("Enter your choice \n");
scanf("%d, &x");
switch(x)
{
case 1: c=a+b;
break;
case 2: c=a-b;
break;
case 3: c=a*b;
break;
case 4: c=a/b;
break;
case 5: c=a%b;
break;
case 6: c=a && b;
break;
case 7: c=a || b;
break;
case 8: c=~a;
break;
case 9: c=a^b;
break;
default: printf("Make correct choice\n");
}
printf("result is: %d",c);
return 0;
}
You are passing a string to scanf function in line number 5 & 8 and no buckets to hold the scanned/read arguments.
The scanf
function's prototype is as follows:
int scanf(const char *format_string, ...);
Where the format_string
is string containing format specifiers
such as %d, %f
...etc
And "..."
in prototype means variable number of arguments. The arguments are buckets to hold the values that scanf
fills by reading the format_string
.
Hence the corrected lines of code should be
line 5. scanf("%d %d", &a,&b);
line 8. scanf("%d", &x);
Another notewothy thing is the variable arguments for scanf
are always pointers to objects.
Syntax of scanf function is
scanf(“format string”, argument list);
So for example, change
scanf("%d %d, &a,&b");
scanf("%d, &x");
to
scanf("%d %d", &a,&b);
scanf("%d", &x);
first of all your input nothing to be scan from your console or any other input.
please check scanf() sysntax.
#include<stdio.h>
int main()
{
int a,b,c,x;
printf("Enter a & b \n"); //printing
scanf("%d %d", &a, &b);
printf("1. add \n 2. sub \n 3. multiply \n 4. div \n 5. mod \n 6. and \n 7. or\n 8. not \n 9. xor \n");
printf("Enter your choice \n");
scanf("%d", &x);
switch(x)
{
case 1: c=a+b;
break;
case 2: c=a-b;
break;
case 3: c=a*b;
break;
case 4: c=a/b;
break;
case 5: c=a%b;
break;
case 6: c=a && b;
break;
case 7: c=a || b;
break;
case 8: c=~a;
break;
case 9: c=a^b;
break;
default: printf("Make correct choice\n");
}
printf("result is: %d",c);
return 0;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.