0

问题是要编写一个程序来从一个文件中读取多组价格和折扣,并选择一个数据结束标记,例如 0 或 -1。它还说在客户必须支付的另一个文件(输出)中打印原始价格、折扣金额和最终价格。

这是我在 input.txt 中写的:

285 30
300 25
0

这是来源:

#include <stdio.h>

int main(void)
{
    FILE * in = fopen("C:\\Users\\Desktop\\c\\price.txt","r");
    FILE * out = fopen("C:\\Users\\Desktop\\c\\priceout.txt","w");

    double price, discountedAmount, finalPrice;
    int disPercent;

    fscanf(in,"%lf",&price);

    while(price != 0) {
        fscanf(in,"%d",&disPercent);
        discountedAmount = price * disPercent / 100;
        finalPrice = price - discountedAmount;
        fscanf(in,"%lf",&price);

        fprintf(out,"The original price is: %.2f\n",price);
        fprintf(out,"The discount amount is: %.2f\n",discountedAmount);
        fprintf(out,"Final Price is: %.2f",finalPrice);
    }
    fclose(in);
    fclose(out);
    return 0;
}

这是程序写入 output.txt 的内容:

The original price is: 300.00
The discount amount is: 85.50
Final Price is: 199.50

The original price is: 0.00
The discount amount is: 75.00
Final Price is: 225.00

程序不应该在 0 处停止吗?我究竟做错了什么?

4

2 回答 2

2

while(price != 0)仅在每个循环开始时检查。不是每次price都变了。

您可以省略第一次阅读,然后执行以下操作:

while (1) {
    fscanf(in,"%lf",&price);
    if (price == 0) // comparing floating point is bad, but I think it's ok here.
        break;
    fscanf(in,"%d",&disPercent);
    discountedAmount = price * disPercent / 100;
    finalPrice = price - discountedAmount;

    fprintf(out,"The original price is: %.2lf\n",price);
    fprintf(out,"The discount amount is: %.2lf\n",discountedAmount);
    fprintf(out,"Final Price is: %.2lf",finalPrice);
}
于 2013-06-04T18:15:55.527 回答
1

在您的代码中...您在错误的位置打印,这就是导致问题的原因..

您首先阅读下一个价格,然后继续...使用下面的代码..

fscanf(in,"%lf",&price);

while(price != 0) {
    fscanf(in,"%d",&disPercent);
    discountedAmount = price * disPercent / 100;
    finalPrice = price - discountedAmount;

    fprintf(out,"The original price is: %.2f\n",price);
    fprintf(out,"The discount amount is: %.2f\n",discountedAmount);
    fprintf(out,"Final Price is: %.2f",finalPrice);
    fscanf(in,"%lf",&price);  // THIS LINE is now after printing previous values..


}
于 2013-06-04T18:20:26.350 回答