第一个C程序中的不寻常行为

时间:2013-10-18 22:45:09

标签: c scanf

我正在编写一个计划,根据他们的收入计算谁应该在家里支付什么。所需的行为如下:

  • 打印欢迎辞,询问家中有多少人。
  • 如果输入的数字是10或以下,请询问他们的姓名。
  • 询问每个人的收入。 < - 这就是问题所在
  • 显示总收入。
  • 计算并显示结果。

显然这个程序不完整,我需要阻止用户输入负值,但最大的问题是当用户输入每个人的收入时,点击返回键时它不会要求更多的用户输入和总收入为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;
}

3 个答案:

答案 0 :(得分:3)

您尚未分配任何内存来保存名称,因此将它们扫描为空。

此后所有赌注都已关闭。

答案 1 :(得分:1)

正如@LoztInSpace指出的那样,names未被分配。

另一个错误是您在&来电中使用%s运算符%fprintf()说明符。它不会按预期给出结果。 另外,你的意图真的是一个要求“人数”的循环吗?

答案 2 :(得分:1)

您在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来电做类似的事情。