gpt4 book ai didi

c++ - 为什么 EOF 在我的 scanf while 循环期间不终止?

转载 作者:行者123 更新时间:2023-11-28 01:29:57 25 4
gpt4 key购买 nike

我刚开始学习 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

这是发生的事情的图像:

Error

我尝试将循环条件更改为 scanf("%d %lf %lf %d", &time, &down, &loan, &record) == 4,但同样的问题发生了。有人可以解释一下我的代码有什么问题吗?

最佳答案

行内

while (scanf("%d %lf %lf %d", &time, &down, &loan, &record) != EOF)

当读取成功时,您希望读取 4 个变量。当 scanf 能够从 stdin 中成功提取所有参数的数据时,它将返回 4。更改检查以使用该数字。

while (scanf("%d %lf %lf %d", &time, &down, &loan, &record) == 4)

关于c++ - 为什么 EOF 在我的 scanf while 循环期间不终止?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51955495/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com