[英]prompting user to play again in C
我已經在另一篇文章中對此進行了詢問,但是沒有一個答案對我的程序有所幫助。 我有一個程序,要求用戶輸入數字並計算均值,中位數和眾數。 然后程序應提示用戶再次玩游戲,如果用戶選擇y或Y,則應重新玩游戲,n或N停止游戲,如果不是,則說無效,請鍵入y或n來提示。你懂了。 這是我的主要內容,也是我的方法goAgain():
#define MAX 25
#include<stdio.h>
#include <stdbool.h>
#include <time.h>
#include <stdlib.h>
int readTotalNums();
void fillArray(int total, int nums[]);
void sortArray(int nums[], int total);
double findMean(int nums[], int total);
double findMedian(int nums[], int total);
int findMode(int nums[], int total);
void printResults(double mean, double median, double mode);
bool goAgain();
int main() {
int nums[MAX];
int total;
double mean, median, mode;
bool b;
do {
total = readTotalNums();
fillArray(total, nums);
sortArray(nums, total);
mean = findMean(nums, total);
median = findMedian(nums, total);
mode = findMode(nums, total);
printResults(mean, median, mode);
b = goAgain();
} while (b==true);
return 0;
}
//其他方法
bool goAgain() {
char *temp;
printf("\nWould you like to play again(Y/N)? ");
scanf("%c", &temp);
while (temp != 'n' && temp != 'N' && temp != 'y' && temp != 'Y') {
printf("\nI am sorry that is invalid -- try again");
printf("\nWould you like to play again(Y/N)? ");
scanf("%c", &temp);
}
if (temp == 'y' || temp == 'Y') {
return true;
} else {
return false;
}
}
每次我玩游戲到提示時,我輸入的任何內容都無濟於事,並且即使輸入的內容是a或N,也總是說無效的重試。感謝您的幫助:)
char *temp;
應該是char temp;
不要將temp
聲明為指針,否則您還沒有為其分配內存。
而是將聲明更改為
char temp;
由於您已經有了正確的答案,因此無需再次說明,因此我將添加一個小技巧。
//this
if (temp == 'y' || temp == 'Y') {
return true;
} else {
return false;
}
//is the same as this
return temp == 'y' || temp == 'Y';
//or more generally
if(condition)
return true
else
return false
//is just
return condition
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.