程序无法正常工作

时间:2017-05-24 07:40:29

标签: c

当我在输入中输入10时,程序就像这样:

Enter item number: 10

Enter unit price: Enter purchase date (mm/dd/yy): Item Unit Purchase

Price Date

10 $0.000 /32764/-572332368

我是否必须创建一个txt文件并输入输入值?

#include<stdio.h>

int main (void)

{

        int item_number, month, day, year;
        float unit_price;

        printf("Enter item number: ");
        scanf("%d", &item_number);

        printf("Enter unit price: ");
        scanf("$%f", &unit_price);

        printf("Enter purchase date (mm/dd/yy): ");
        scanf("d%/d%/d%", &month, &day, &year);

        printf("Item Unit Purchase\n");
        printf("Price Date\n");
        printf("%-d $%.2f%-02d/%02d/%02d\n", item_number, unit_price, month, day, year);

  return 0;

}

3 个答案:

答案 0 :(得分:1)

将“$%f”更改为“%f”,将“d%”更改为“%d”,看看是否有帮助

答案 1 :(得分:1)

您需要检查scanf()是否“有效”。

以两个scanfs为例

if (scanf("$%f", &unit_price) != 1) {
    fprintf(stderr, "scanf error at line %d.\n", __LINE__ - 1);
    exit(EXIT_FAILURE);
}

if (scanf("d%/d%/d%", &month, &day, &year) != 3) {
    fprintf(stderr, "scanf error at line %d.\n", __LINE__ - 1);
    exit(EXIT_FAILURE);
}

答案 2 :(得分:1)

这些是你得到的警告。我建议你仔细阅读这些警告,这将有助于你理解这个问题:

warning: unknown conversion type character ‘/’ in format [-Wformat=]
         scanf("d%/d%/d%", &month, &day, &year);
               ^
:17:15: warning: unknown conversion type character ‘/’ in format [-Wformat=]
:17:15: warning: spurious trailing ‘%’ in format [-Wformat=]
:17:15: warning: too many arguments for format [-Wformat-extra-args]
:21:16: warning: '0' flag ignored with '-' flag in gnu_printf format [-Wformat=]
         printf("%-d $%.2f%-02d/%02d/%02d\n", item_number, unit_price, month, da

您需要知道STDIN与STDOUT printf()scanf() format specifier usage的使用情况。通过这个链接,它会帮助你。

刚刚修改了您的代码:

#include <stdio.h>
int main (void) {

        int item_number, month, day, year;
        float unit_price;

        printf("Enter item number: ");
        scanf("%d", &item_number);

        printf("Enter unit price: ");
        scanf("$%f", &unit_price);

        printf("Enter purchase date (mm/dd/yy): ");
        scanf("%d, %d, %d", &month, &day, &year);

        printf("Item Unit Purchase\n");
        printf("Price Date\n");
        printf("%d $:%.2f /%d/ %02d, %02d\n", item_number, unit_price, month, day, year);

  return 0;
}

<强>输出:

Enter item number: 10
Enter unit price: Enter purchase date (mm/dd/yy): 2/6/8
Item Unit Purchase
Price Date
10 $:0.00 /2/ 00, 1183423824