I am writing code using Scanf and i want it to take in three different inputs at once perform some computations using those inputs and give me an output but it is not working as i expected .
Firstly it is only taking one function and is also displaying the values next to where the inputs are going that is the 100s, 200s, and 500s which you will see please help me with some clarity.
The code is;
# include<stdio.h>
int main () {
//input
double a=100,b=200,c=500;
int d,e,f;
printf("Please enter the number of coins you have for each denomination belown");
printf("If you have no coins in that denomination input zero.n");
scanf("100s:%lf",&d);
scanf("200s;%lf",&e);
scanf("500s:%lf",&f);
//computation
double g=(double)((a*d)+(b*e)+(c*f));
//output
printf("Change is shs:%lf",g);
}
I was expecting my terminal to display the following:
100s:
200s:
500s:
then
Change is shs:
But it is not
12
I was expecting my terminal to display the following:
100s:
200s:
500s:
Evidently, then, you were expecting scanf()
to produce output to the terminal (100s:
, 200s:
, 500s:
) before reading input. scanf
does not do that. It is an input function only. If you want to print prompts, then use an output function such as printf
.
Additionally, the pointers you provide for storing converted input must be type-matched to the conversion specifiers in your format. %lf
should be matched with a pointer to double
, but you are matching it with pointers to int
. If you want to input signed integers then use specifier %d
. If you want to input decimal floating point numbers then switch the types of your variables to double
.
For example,
double d, e, f;
// ...
printf("100s:");
fflush(stdout); // flush the output buffer so the prompt is shown right away
scanf("%lf",&d);
Furthermore, you may want to add a n
to the end of the format for the last printf()
. Otherwise, there won’t be a newline between the end of the program’s output and the next shell prompt.
5