08.01.2023 Views

Learn to Program with C_ Learn to Program using the Popular C Programming Language ( PDFDrive )

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Chapter 3 ■ Programs with Sequence Logic

When entering data for a float/double variable, an integer is acceptable. If you enter 42,

say, it will be interpreted as 42.0. But, as discussed above, if you enter a floating-point constant

(e.g., 2.35) for an int variable, it will be truncated (to 2, in this example).

If you need to, you can read values into more than one variable using one scanf statement.

If x and y are double variables, you can use

scanf("%lf %lf", &x, &y);

to read values into x and y. When executed, scanf expects to find two valid floating-point

(or integer) constants next in the data. The first is stored in x and the second in y. Any number of

spaces or blank lines can come before, between, or after the numbers.

You can also read values for int, double, or float variables in the same scanf statement.

You just have to ensure that you use the correct specification for each variable. Suppose item and

quantity are int, and price is double. The statement

scanf("%d %lf %d", &item, &price, &quantity);

expects to find three numbers next in the data.

• The first must be an int constant that will be stored in item.

• The second must be a double (or int) constant that will be stored in price.

• The third must be an int constant that will be stored in quantity.

The following are all valid data for this scanf statement:

4000 7.99 8.7 // 8.7 is truncated to 8

3575 10 44 // price will be interpreted as 10.00

5600 25.0 1

As usual, any amount of whitespace may be used to separate the numbers.

The following are all invalid data for this scanf statement:

4000 7.99 x.8 // x.8 is not an integer constant

25cm 10 44 // 25cm is not an integer constant

560 25 amt = 7 // a is not a valid numeric character

When scanf fetches a number, it remains poised just after the number; a subsequent scanf

will continue to read data from that point. To illustrate, suppose some data is typed as

4000 7.99 8

and consider the statements

scanf("%d", &item);

scanf("%lf", &price);

scanf("%d", &quantity);

53

www.it-ebooks.info

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!