我正在编写一个程序,根据他们的收入确定谁应该在家庭中支付什么。所需的行为如下:
- 打印欢迎信息并询问家里有多少人。
- 如果输入的数字是 10 或以下,请询问他们的姓名。
- 询问每个人的收入。<-这就是问题所在
- 显示总收入。
- 计算并显示结果。
显然这个程序不完整,我需要阻止用户输入负值,但最大的问题是当用户输入每个人的收入时,在按下返回键时它不再要求用户输入并且 totalEarnings 出来了为 0。
我习惯用 C++ 编程,所以我希望我刚刚错过了 C 的一个怪癖。
主程序
#include <stdio.h>
int main(void){
short numberOfPeople = 0;
char* names[10] = {0,0,0,0,0,0,0,0,0,0};
float earnings[10] = {0,0,0,0,0,0,0,0,0,0};
float totalEarnings = 0;
float bills = 0;
printf("Welcome!\nThis program calculates who should pay what for the bills in a proportional manner, based upon each persons income.\nHow many people are in your household?\n\n");
do {
printf("You can enter up to 10: ");
scanf("%d", &numberOfPeople);
} while(numberOfPeople > 10);
puts("");
for(short j = 0; j < numberOfPeople; ++j){
printf("What is person %d's name? ", j+1 );
scanf(" %s", &names[j]);
}
puts("");
for(short i = 0; i < numberOfPeople; ++i){
printf("How much did %s earn this month? ", &names[i]);
scanf(" %.2f", &earnings[i]);
totalEarnings += earnings[i];
}
printf("\nTotal earnings are %.2f.\n\n", &totalEarnings);
printf("How much are the shared bills in total? ");
scanf(" %.2f", &bills);
puts("");
for(short k = 0; k < numberOfPeople; ++k){
printf("%s should pay %.2f", &names[k], &bills);
}
puts("");
return 0;
}