如何获取任何整数,例如10050,并将其输出为$ 100.50?

0 c printf

例:

int amount = 10050;
printf("format_string", amount);
// What should the format string look like to get $100.50 as the output?
Run Code Online (Sandbox Code Playgroud)

是否有可能告诉printf函数我想要从右边放两个数字点而不做这样的事情:

int amount = 10050;
printf("$%d.%02d", amount / 100, amount % 100); // Output: $100.50
Run Code Online (Sandbox Code Playgroud)

Bar*_*mar 5

您可以将其转换为float除以100,然后使用浮动格式打印.

printf("$%.2f", ((double)amount)/100);
Run Code Online (Sandbox Code Playgroud)

  • 如果`amount`是要转移的类型,则不会.但你可以交替写`amount/100.0`(这可能更容易阅读). (3认同)