gpt4 book ai didi

c - 如何让程序在询问 y 或 n 时重复

转载 作者:行者123 更新时间:2023-11-30 14:45:53 24 4
gpt4 key购买 nike

我试图让这个程序在提示 Y 或 N 时重复,但由于某种原因我似乎无法让它正常工作,这是我剩下的最后一件事,我很确定代码的其余部分是正确的我认为我需要的是如果用户输入“Y”则重复整个程序,或者如果用户输入“N”则退出

 int main(void)
{
// Constant and Variable Declarations
const int MPH_SPEED_MIN = 1;
const int MPH_SPEED_MAX = 100;
const int HOURS_TRAVLED_MIN = 1;
int mphSpeed = 1;
int hoursEntered = 0;
int distanceTraveled = 0;
int counterNum = 0;
int distanceNum = 0;
char ch = 'y';



// *** Input ***
do {
printf("What is the speed of the vehicle in MPH? ");
scanf("%d", &mphSpeed);
while ((mphSpeed < MPH_SPEED_MIN) || (mphSpeed > MPH_SPEED_MAX)) {
printf("\tThe speed entered must be between %d and %d inclusive
\n",MPH_SPEED_MIN, MPH_SPEED_MAX);
printf("\tPlease re-enter the speed of the vehicle in MPH: ");
scanf("%d", &mphSpeed);
}

printf("How many hours has it traveled? ");
scanf("%d", &hoursEntered);

while (hoursEntered < HOURS_TRAVLED_MIN) {
printf("\tThe hours traveled must be a positive number.\n");
printf("\tPlease re-enter the number of hours traveled: ");
scanf("%d", &hoursEntered);
}
printf("\n");
printf("Hour\tDistance Traveled\n");
distanceTraveled = hoursEntered * mphSpeed;
for (counterNum = 1; counterNum <= hoursEntered; counterNum++) {
distanceNum = distanceTraveled * counterNum;
printf("%d\t%d miles\n", counterNum, distanceNum);
}
printf("\n");
printf("Run the program again (Y/N)? ");
scanf("%c", &ch);
printf("\n");
} while (ch == 'Y' || ch == 'y');


; return 0;

最佳答案

当使用 scanf(%c... 读入时,该语句很可能会从先前的输入中读入缓冲区中留下的新行字符。而是读入字符串,因为 %s 忽略任何前导空格(包括缓冲区中留下的换行符)。

尝试...

  char exitYN[2];
if (scanf("%1s",exitYN) != 1) {
exitYN[0]='N';
}
char ch = exitYN[0];
} while (ch == 'Y' || ch == 'y');

关于c - 如何让程序在询问 y 或 n 时重复,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52693169/

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