gpt4 book ai didi

c - 我的代码不断重复,不允许用户输入

转载 作者:行者123 更新时间:2023-11-30 16:19:42 25 4
gpt4 key购买 nike

嘿,我已经编写了一个包含各种函数的 C 代码,但是我在代码末尾遇到了问题。这是我的代码的 main 函数

int main() {
do {
printf("-- Wind turbine power calculator -- \n");

/*defining variables for each function,
Cp = performance coefficient,
Ng = generator efficiency,
Nb = gearbox efficiency,
V = velocity,
hA = horizontal area,
vA = vertical area,
d = rotor diameter,
h = rotor height,
a = altitude,
t = type of turbine */

double t, V, Cp, Ng, Nb, p, Pwr, d, a, h, hA, vA, A;
char ch, n, y, N, Y;

t = getType();
d = getDiameter();
h = getHeight();
a = getAltitude();
V = getVelocity();
Cp = getPerformance();
Ng = getGenerator();
Nb = getGearbox();
p = density(a);
hA = hArea(d);
vA = vArea(d, h);

/*setting the area in the power equation to equal the calculated vertical or horizontal area depending on the input from user*/

if (t == 'v' || t == 'V') {
A = vA;
} else if (t == 'h' || t == 'H') {
A = hA;
}

/*calculating the power of the wind turbine calling on the functions within the code*/

Pwr = A * p * Cp * 0.5 * Ng * Nb * V * V * V;

printf("The turbine power is %0.0lf KW\n", Pwr);

/*asking the user if they want to continue the program, if not the program will end*/

printf("\nDo you want to continue (y/n):");
scanf("%c", & ch);

if (ch == 'n' || ch == 'N')
break;
printf("\nThe program has been terminated\n");
}while (1);

return 0;
}

我在最后一部分遇到问题



/*asking the user if they want to continue the program, if not the program will end*/

printf("\nDo you want to continue (y/n):");
scanf("%c", & ch);

if (ch == 'n' || ch == 'N')
break;
printf("\nThe program has been terminated\n");
}while (1);

return 0;
}

当代码到达这部分时,它只是自动重复自身,并且不允许用户输入其输入,然后决定是否应该再次运行或终止。

关于如何解决这个问题有什么想法吗?我认为一种方法可能是与 scanf 属性有关,但我不是 100% 确定。

谢谢你的帮助

最佳答案

您遇到的问题是您没有清除输入缓冲区。

因此,当您使用 scanf("%c", &ch); 时,它没有获得您刚刚输入的 key ,而是您之前输入的 key 。

此键可能是在您上次检查他们是否想要继续该程序时输入的,或者是在您的某个功能中输入的。

无论如何,解决方案是在获取输入之前编写 fflush(stdin);

此外,您是否注意到 if 语句末尾的括号不匹配?这与您的问题不符,所以我只是认为您提出问题时是一个错误。

你的缩进真的很烦人,我花了太长时间才理解你的代码。

关于c - 我的代码不断重复,不允许用户输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55544953/

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