【发布时间】:2018-08-21 19:31:18
【问题描述】:
我刚开始学习 C++,正在尝试学习如何使用 scanf 和 printf 来加快输入和输出。这是我目前正在处理的代码:
#include <stdio.h>
using namespace std;
int main() {
int time, record;
double down, loan;
while (scanf("%d %lf %lf %d", &time, &down, &loan, &record) != EOF) {
double value = down + loan;
double owed = loan;
double payment = owed/time;
// current simulated month and depreciation
int rday, c = 0;
double temp, dep;
bool found = false;
// finds value and owed after records
while (!found && record > 0) {
scanf("%d %lf", &rday, &temp);
// adjusts value and owed to day before listed on record
while (!found && c <= rday) {
if (c == rday) {
dep = temp;
}
value *= 1 - dep;
if (c > 0) {
owed -= payment;
}
c++;
// determines if found date
if (owed < value) {
found = true;
}
}
record--;
}
// finds point where owed < value
while (!found && value < owed) {
value *= 1 - dep;
owed -= payment;
c++;
}
if (c - 1 == 1) {
printf("%d month\n", c - 1);
}
else {
printf("%d months\n", c - 1);
}
}
return 0;
}
当我在 Code::Blocks 上运行它时,它会打印正确的答案,但即使我输入 CTRL+Z(我使用的是 Windows),最外面的 while 循环也不会终止。这是我的输入:
30 500.0 15000.0 3
0 .10
1 .03
3 .002
12 500.0 9999.99 2
0 .05
2 .1
60 2400.0 30000.0 3
0 .2
1 .05
12 .025
-99 0 17000 1
这是发生了什么的图片:
我尝试将循环条件更改为scanf("%d %lf %lf %d", &time, &down, &loan, &record) == 4,但同样的问题发生了。有人可以解释一下我的代码有什么问题吗?
【问题讨论】:
-
".. 学习 C++ 并且正在尝试学习如何使用 scanf 和 printf 更快" --> 考虑学习流
<<和>>。为 C 保存scanf和printf。 -
为什么代码不检查
scanf("%d %lf", &rday, &temp);的返回值?我怀疑这是“最外面的while循环没有终止”的来源,因为内部从未完成。要么是那个,要么你没有正确地发出 end-of-file 信号。 -
在“ctrl+z”之后按“enter”可以吗?
Ctrl+z只是将EOF添加到标准输入,但scanf仅在按下enter时处理。 -
如何确定代码没有卡在
while (!found && value < owed)? -
nitpick: 代替 '#include
' 使用 '#include ' 见stackoverflow.com/questions/10460250/cstdio-stdio-h-namespace
标签: c++