Professional Documents
Culture Documents
4 Reading Data
4 Reading Data
Reading Data
Then
42 -7 v8
or
42= 18 24
Reading Data Into a float Variable
If we wish to read a floating-point number into a float variable x,
we can use:
scanf("%f", &x);
When executed, scanf expects to find a valid floating-point constant
in the data.
For example, any of the following will be acceptable:
4.265
-707.96
2.345E+1
In the last case, there must be no spaces, for instance, between the 5 and
the E or between the E and the + or between the + and the 1.
The following will all be invalid for reading the number 23.45:
2.345 E+1
2.345E +1
2.345E+ 1
Reading Data Into a double Variable
If we wish to read a floating-point number into a double variable,
y, we can use:
scanf("%lf", &y);
Note that the specification %lf (percent ell f) is used to read a value into a
double variable.
Be careful: you cannot use %f for reading data into a double variable. If you
do, the value read will be stored in 32 bits rather than 64 bits.
You can read values into more than one variable using one scanf
statement.
Example: If x and y are double variables, you can use:
scanf("%lf %lf", &x, &y);
Note that:
When entering data for a float/double variable, an integer is
acceptable.
If you enter 42, say, it will be interpreted as 42.0.
Reading Data Into a double Variable
Note that:
If you enter a floating-point constant e.g., 2.35 for an int variable, it
will be truncated to 2.
%lf is used to read a value into a double variable.
%f is used to read a value into a float variable.
%f is used to print the value of a float or double variable.
You can read values for int, double, or float variables in the same
scanf statement.
Example: Suppose item and quantity are int, and price is double.
Sol:
f
Examples (Average)
Notes:
We use 3.0 instead of 3 in calculating the average. This forces a
floating point division to be performed.
If we had used 3, an integer division would be performed,
giving 13.0 rather than 13.3 as the answer for the sample
data, above.
We could calculate and print the average in the printf statement
with
printf("\nTheir average is %f\n", (a + b + c) / 3.0);
Examples (Banking)
Write a program to read the data for a customer in a bank: name, account
number, average balance, and number of transactions made during the
month, then calculate the interest earned and service charge.
The interest is calculated as follows:
interest = 6% of average balance
The service charge is calculated by this:
service charge = 50 cents per transaction
Finally the program print the customer’s name, average balance, interest
earned, and service charge.
The following is a sample run of the program:
Examples (Banking)
Sol: