【问题标题】:prompting user to play again in C提示用户在 C 中再次播放
【发布时间】:2012-03-14 14:12:36
【问题描述】:

我已经在另一篇文章中询问过,但没有一个答案对我的程序有帮助。我有一个程序要求用户输入数字并计算平均值、中位数和众数。然后程序应该提示用户再次玩,如果用户选择y或Y它应该重新玩游戏,n或N停止,如果不是这样,说无效,请输入y或n到bla bla你懂了。这是我的主要方法,也是我的方法 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;
}
}

每次我玩游戏时,它都会出现提示,我输入的任何内容都不会执行任何操作,并且一直说无效再试一次,即使输入的是 ay 或 N。感谢您的帮助 :)

【问题讨论】:

标签: c arrays main scanf prompt


【解决方案1】:

char *temp; 应该是char temp;

【讨论】:

    【解决方案2】:

    不要将temp 声明为指针,你也没有为它分配内存。

    改为将您的声明更改为

    char temp;

    【讨论】:

      【解决方案3】:

      既然你已经有了正确的答案,就不用再说了,所以我再补充一点。

      //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
      

      【讨论】:

        猜你喜欢
        • 2012-03-11
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多