










5 .假设一个程序的开头是这样:
#define BOOK "War and Peace" int main(void) {
float cost =12.99; float percent = 80.0;
}
请构造一个使用BOOK、 cost和percent的printf()语句, 打印以下内容:
This copy of "War and Peace" sells for $12.99.
That is 80% of list.
根据题目要求,需要构造一个 printf() 语句,使用定义的宏 BOOK 和变量 cost、percent 来打印指定内容。
#include <stdio.h> #define BOOK "War and Peace" int main(void) { float cost = 12.99; float percent = 80.0; printf("This copy of \"%s\" sells for $%.2f.\nThat is %.0f%% of list.\n", BOOK, cost, percent); return 0; }
| 要打印的内容 | 使用的格式符 | 说明 |
|---|---|---|
"War and Peace" |
\"%s\" |
外层用 \" 打印双引号,%s 输出字符串 |
$12.99 |
$%.2f |
%.2f 保留2位小数 |
80% |
%.0f%% |
%.0f 不显示小数,%% 打印一个 % 符号 |
This copy of "War and Peace" sells for $12.99. That is 80% of list.
1、打印双引号:使用 \" 转义字符
\"%s\" → 输出 "War and Peace"2、打印百分号:使用 %% 转义
%.0f%% → 输出 80%%,编译器会将其误认为是格式说明符的开始3、浮点数格式:
%.2f → 保留2位小数(12.99)%.0f → 不保留小数(80)4、换行:使用 \n 实现两行输出
如果需要更清晰的代码结构,也可以分两次调用 printf():
printf("This copy of \"%s\" sells for $%.2f.\n", BOOK, cost); printf("That is %.0f%% of list.\n", percent);
或者使用多个 % 占位符:
printf("This copy of \"%s\" sells for $%.2f.\nThat is %.0f%% of list.\n", BOOK, cost, percent);
BOOK 宏已经包含双引号("War and Peace"),所以在 printf 中直接用 %s 即可
%% 在 printf 中用于输出一个百分号字符
%.0f 会四舍五入到整数(80.0 → 80)
此内容由惯性聚合(RSS阅读器)自动聚合整理,仅供阅读参考。 原文来自 — 版权归原作者所有。