我正在尝试让该程序在出现提示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;
答案 0 :(得分:1)
使用scanf(%c...
读入时,该语句很可能从先前的输入中读取缓冲区中剩余的换行符。而是读一个字符串,因为%s
会忽略任何前导空格(包括缓冲区中留下的换行符)。
尝试...
char exitYN[2];
if (scanf("%1s",exitYN) != 1) {
exitYN[0]='N';
}
char ch = exitYN[0];
} while (ch == 'Y' || ch == 'y');
答案 1 :(得分:0)
这里可以做的最小,最有效的更改是,在接受<space>
或%c
的同时,在Y
之前添加N
,即{ {1}}
我不知道以下内容是否是在StackOverflow中键入代码时出现的错误,或者它们原本是代码中的错误,但绝对值得进行更改:
scanf(" %c, &ch");
,#include<stdio.h>
之前使用多余的分号(;
)return
之后,结尾缺少右括号(}
)。这是工作代码:
return
我还附上了输出,以防万一您需要验证。
输出:
MPH中的车速是多少? 12
它旅行了几个小时? 1
旅行时的距离
1 12英里
再次运行程序(是/否)? y
MPH中的车速是多少? 6
它旅行了几个小时? 6
旅行时的距离
1 36英里
2 72英里
3108英里
4144英里
5180英里
6216英里
再次运行程序(是/否)? n