gpt4 book ai didi

c - 函数调用后通过我的 if else 运行的程序

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

我在 C 中有一个类作业,用于制作一个执行三个计算的简单计算器。我还没有完成所有功能,但我的 calcMenu 功能有问题。当函数被调用时,程序会运行所有的 if else 语句并且我不知道,它只执行错误检查的 else 语句。然后该函数再次运行,这是预期的,但这次它不会运行所有 if else 语句并允许用户做出选择。我知道我做了一些非常愚蠢的事情,但在过去的一个小时里我一直在绞尽脑汁。如果有人对我有任何遗憾,请指出正确的方向。我知道所有的系统调用都会让一些人感到厌烦,但这是一门基础类(class),我们的讲师告诉我们要使用它们。

提前致谢

迈克

#include <stdlib.h>
#include <stdio.h>
#include <ctype.h>
#define pause system ("pause")
#define cls system ("cls")

//Prototype calculate functions here
void evenOrOdd(int userNumber);
void squareNum(int userNumber);
void cubeNum(int userNumber);
void calcMenu(int userNumber);

void main() {
//Declare local variables here
int userNumber = 0;
printf("\t\t\tThe amazing three function caluculator\n\n\n");
printf("Please enter a whole number that you would like to calculate\n");
scanf("%d", &userNumber);


calcMenu(userNumber);
}



void calcMenu(int userNumber)
{
char calculateOption;
printf("\nWhat calculation would you like to perform with your number?\n\n");
printf("Press A.) to check if your number is even or odd.\n\n");
printf("Press B.) to calculate the square of your number.\n\n");
printf("Press C.) to calculate the cube of your number.\n\n");
printf("press D.) to exit the program.\n");
scanf("%c", &calculateOption);
calculateOption = toupper (calculateOption);



if (calculateOption == 'A')
{
evenOrOdd(userNumber);
}
else if (calculateOption == 'B')
{
squareNum(userNumber);
}
else if (calculateOption == 'C')
{
cubeNum(userNumber);
}
else if (calculateOption == 'D')
{
system("cls");
printf("Thank You for using my amazing calculator.\n\n");
system ("pause");
system ("exit");
}
else
{
printf("Please enter a valid choice");
calcMenu(userNumber);
}


}


void evenOrOdd(int userNumber) {
userNumber = userNumber %2;
if (userNumber == 0)
{
printf("Your number is even. \n");
}
else
{
printf("Your number is odd. \n");
}

}
void squareNum(int userNumber) {

}
void cubeNum(int userNumber){

}

最佳答案

当您使用 scanf 读取输入时,您必须按 Enter 键才能使程序继续。您的 scanf 调用从输入中读取单个字符,但将 Enter 键留在输入缓冲区中,以便在您下次调用 scanf.

有一个非常简单的技巧可以解决这个问题:在 scanf 格式字符串的 "%c" 之前或之后放置一个空格。这将使 scanf 跳过空格。

scanf("%c ", &calculateOption);

如果您使用调试器单步执行代码,您会很容易地看到 calculateOption 将成为换行符。

关于c - 函数调用后通过我的 if else 运行的程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14370300/

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