gpt4 book ai didi

c - 我的主 while 循环将运行,并在用户输入 'y' 或 'n' 时再次运行。不管用户怎么说

转载 作者:太空宇宙 更新时间:2023-11-04 02:29:02 25 4
gpt4 key购买 nike

当我添加主 while 循环时,程序总是运行,然后再次运行并显示一条消息告诉我存在无效数据(来 self 的第一次输入验证)。谁能告诉我如何让用户选择结束程序?基本上,我只想让用户可以选择按“y”或“n”来结束程序。愿意听取新想法,例如使用 for 或 do while 循环!我只想让程序通过。我希望用户能够通过任意多次,同时可以选择在每次通过后离开。

#include <stdio.h>

//Declare functions
void displayWelcome(void);
double getAverage(double yards, double carries);
void endMessage(void);


int main()
{
//Declare variables
double yards, carries, average, bestAverage;
char again = 'y';
//Call function to display welcome message
displayWelcome();

while (again == 'y' || again =='Y') {
//Prompt user for the number of yards,
printf("Enter the number of yards:");
/*
Scan in the value of 'yards' and send user into a loop if they enter
incorrect data
While loop to validate the data of the value 'yards'
*Works with a numerical value greater than 0
*/
while ( 1 != scanf( "%lf", &yards ) || yards <= 0)
{

fflush(stdin);
printf("Enter a numerical value greater than zero:");
}
//Prompt user for the number of carries, followed by an input scan to get
//value of carries
printf("Enter the number of carries:");
/*
Scan in the value of 'yards' and send user into a loop if they enter
incorrect data
While loop to validate the data of the value 'carries'
*Works with a numerical value greater than zero
*/
while ( 1 != scanf("%lf", & carries) || carries <= 0)
{
//Refreshes the input value of the variable 'carries' and prompts the
//user to type in new value for 'carries'
fflush(stdin);
printf("Enter a numerical value greater than zero:");
}

average = getAverage( yards, carries);
printf("yards:%g carries:%g average:%g\n", yards, carries, average);
//Give the user the option to run the program again
printf("Would you like to run the program again? Enter (y)es or (n)o\n");
scanf("%c\n", &again);
}
endMessage();
return 0;
}

void displayWelcome(void)
{
printf("Welcome to Football Stats\n");
}

double getAverage(double yards, double carries)
{
double average;
average = yards + carries / 2;
return average;
}
void endMessage(void){
printf("\nThese results were brought to you by ");
}

更新(问题仍未回答) 当我按“n”停止程序时它起作用了。但是,当我按“y”再次运行它(使用新输入的代码)时,它也会停止程序。回到我的问题,任何人都可以看到我做错了什么,以便我可以让用户选择关闭程序吗?

最终更新 我发现了这个问题。我做了 "scanf("%c\n", &again);"(清除值)当我应该放置“scanf(”\n%c“,&again);”。感谢所有花时间帮助我的人!

最佳答案

while (again == 'y' || 'Y') { ...

|| 不是那样工作的。 &&||用于连接完整的 bool 表达式。你的意思是:

while (again == 'y' || again == 'Y') { ...

在 C 中,表达式 'Y' 只是整数 89,C 将其解释为“真”,因为它不是零。因此,您的第一个表达式是

while (<something> || <true>) { ...

这总是正确的。

关于c - 我的主 while 循环将运行,并在用户输入 'y' 或 'n' 时再次运行。不管用户怎么说,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46553727/

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