gpt4 book ai didi

c - 从用户定义的函数返回使我的程序崩溃

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

所以我的目标是在函数内部将菜单选项作为输入getMenuInput(); (1-4) 并将其返回到 main() 以与 switch case 一起使用。此代码已简化,但我打算轮询两个 vector 并对它们执行操作。我一生都无法弄清楚为什么它在从函数返回时停止,而没有到达开关盒。我什至尝试在返回后立即在行中打印文本,但没有得到任何输出。

作为旁注,您只有 3 次机会输入正确的菜单选项,否则程序将退出并打印错误。这(或者更确切地说,我实现这一目标的方法)可能是这里的问题吗?

这是我的代码:

#include <stdio.h>

/* This is a structure to hold the two parts
of the vector in a single variable */
typedef struct
{
float x;
float y;
} vect;

char getMenuInput(void);

int main(void)
{
/* declaration of variables */
vect vector1, vector2;
char menuInput = 0;
int counter = 0;

while ((counter < 3) && (menuInput == 0))
{
printf("--- Menu ---\n"
"1 Add two vectors\n"
"2 Subtract two vectors\n"
"3 Calculate Euclidian Distance\n"
"4 Exit the program\n"
" Please select an option (1, 2, 3, or 4): ");

menuInput = getMenuInput(); /* 3 chances */

switch (menuInput)
{
case 1:
{
printf("You selected 'Add'\n");
break;
}/* Add vectors */

case 2:
{
printf("You selected 'Subtract'\n");
break;
}/* Subtract vectors */

case 3:
{
printf("You selected 'Euclidian Distance'\n");
break;
}/* Euc Distance */

case 4:
{
printf("You selected 'Exit'\n");
break;
}/* exit */

default:
{
printf(" >Invalid option!\n");
menuInput = 0;
++counter;
}
}
}
if (counter == 3)
printf("Program error - Too many invalid inputs");
else
return (0);

/* Receive the two vectors (float or int, +ve or -ve */
/* This repeats until they're entered correctly */


/* Find the solution, operation found in the menu */
/* Float, 2dp precision */
}

char getMenuInput(void)
{
char temp;
scanf("%d", &temp);
return (temp);
}

我得到的输出是这样的:

--- Menu ---
1 Add two vectors
2 Subtract two vectors
3 Calculate Euclidian Distance
4 Exit the program
Please select an option (1, 2, 3, or 4): 1

RUN SUCCESSFUL (total time: 870ms)

请帮忙。我要把头发扯下来。

最佳答案

char temp;
scanf("%d", &temp);

temp 是一个字符(1 个字节),但您试图将一个整数(可能是 4 或 8 个字节)读入其中?这是未定义的行为,很可能会导致崩溃。

关于c - 从用户定义的函数返回使我的程序崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49979033/

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