问题是写一个程序,从文件中读取几组价格和折扣,选择数据结束标记,如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吗?我做错了什么?
答案 0 :(得分: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);
}
答案 1 :(得分: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..
}