编写一个程序,提示用户从键盘输一个星期的薪水(以美元为单位)和工作时数,它们均为浮点数,然后计算并输出每个小时的平均薪水,输出格式如下所示:
Your average hourly pay rate is 7 dollars and 54 cents.
#include <stdio.h> int main(int argc, char** argv) { float salary = 0.0f; float time = 0.0f; float avg = 0.0f; int a = 0; printf("Please enter a week‘s salary(In us dollars for the unit):\n"); scanf("%f",&salary); printf("Please enter a week of work time:\n"); scanf("%f",&time); avg = salary/time; a = (int)avg; avg = (avg-a)*100; printf("Your average hourly pay rate is %d dollars and %2.0f cents.",a,avg); return 0; }
这里需要对获得的结果分别输出整数和小数部分。所以先声明一个整型变量a,强制转换avg的值,获得整数部分。然后用avg的值减去a的值,获得小数部分乘100,输出的时候%2.0f 宽度为2小数点后为0.来输出美分的部分。
时间: 2024-10-24 14:17:09