Re: scanf and conversion problem
- From: yxxxxy <yxx_happy@xxxxxxxxxxx>
- Date: Fri, 31 Oct 2008 00:14:29 -0700 (PDT)
On 10月30日, 下午12时16分, Peter Nilsson <ai...@xxxxxxxxxxx> wrote:
yxxxxy <yxx_ha...@xxxxxxxxxxx> wrote:
Hi, this is a part of my program code.
i want to ask two questions.
int time;
float rate;
float salary;
printf("Enter # of hours worked (-1 to end):");
scanf("%d",&time);
while (time!=-1) {
printf("Enter hourly rate of the worker ($00.00):");
1 scanf("%f",&rate);
if (time>=40)
2 salary=(time-40)*3/2*rate+40*rate;
else
salary=time*rate;
printf("Salary is $%.2f\n",salary);
printf("Enter # of hours worked (-1 to end):");
scanf("%d",&time);
}
first question:
there is no error and warning.
but
when i change 3/2 to 1.5 (line 1), it will reveals a
warning :conversion from 'double' to 'float', possible
loss of data why?
Because multiplying an integer by 3 and dividing by 2
produces an integer. Multiplying an integer by 1.5 will
produce a double (since 1.5 is of type double). As
doubles usually have more precision that floats, the
compiler has decided to warn that you are storing a
double value into a float. [It doesn't have to, but
yours did.]
second question:
when i change "%f" to " %f",there is no change in result.
Read the spec for scanf. All you've done is asked scanf
to ignore optional leading whitespace twice.
but when i change it to "%f " , it will stop at
this line .
Because a space is a conversion directive in its own right.
Find out what it is by reading the specs.
and when i change it to "% f",
That is not a valid conversion directive. Undefined
behaviour is allowed to do anything.
Big Tip: C is the worst language to learn by experimentation.
--
Peter- 隐藏被引用文字 -
- 显示引用的文字 -
Thank you very much!
And thank your tip!
.
- References:
- scanf and conversion problem
- From: yxxxxy
- Re: scanf and conversion problem
- From: Peter Nilsson
- scanf and conversion problem
- Prev by Date: Re: floating point number help
- Next by Date: Re: srand
- Previous by thread: Re: scanf and conversion problem
- Next by thread: Han from China helps you with your killfile
- Index(es):
Relevant Pages
|