我正在编写一个程序,根据他们的收入来确定谁应该在家庭中支付多少钱。所需的行为如下:
显然,此程序尚未完成,我需要停止用户输入负值,但是最大的问题是,当用户输入每个人的收入时,在按返回键时它不再要求用户输入,并且总收益会出现为0。
我习惯于使用C ++进行编程,所以希望我刚刚错过了C的怪癖。
main.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;
}
您&
在printf调用中存在多余字符的问题,其他人已经注意到。
您报告的问题很可能是由以下原因引起的:
scanf(" %.2f", &earnings[i]);
问题在于,.
在scanf格式中没有定义的含义(它可能被忽略,或者可能导致scanf调用失败。)将2
输入限制为2个字符,因此,如果任何人的收入超过2个字符,则输入将失败数字。因此,您需要摆脱这些障碍,而您真正需要的是检查scanf的返回值以查看其是否失败,并进行适当的处理。就像是:
while (scanf("%f", &earnings[i]) != 1) {
scanf("%*[^\n]"); /* throw away the rest of the line */
printf("That doesn't look like a number, what did they earn this month? ");
}
所有其他scanf
调用都应执行类似的操作。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句