gpt4 book ai didi

C 程序总是使用 1503657284 或 -1863345812 作为输入的 scanf 选择

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

我正在学习 C 编程。在下面的程序中,我有 6 个选择。用户做出 6 个选择之一,程序打印一些信息。这一直持续到用户说退出。当我执行程序时,选择 始终是 1503657284,但当我按 6 时程序正常退出。我在 Fedora 上使用 Eclipse。

代码在这里。

#include <stdio.h>
#include <stdlib.h>

int main(void) {
int choice = 0;
printf("Welcome to the program\n");

while(choice != 6) {
printf( "1. CHOICE 1\n"
"2. CHOICE 2\n"
"3. CHOICE 3\n"
"4. CHOICE 4\n"
"5. CHOICE 5\n"
"6. Quit\n"
"Please enter your choice: \n");
scanf("%d", &choice);
printf("You made %d as your choice\n", &choice);
switch(choice) {
case '1' :
printf("CHOICE 1\n");
break;
case '2' :
printf("CHOICE 2\n");
break;
case '3' :
printf("CHOICE 3\n");
break;
case '4' :
printf("CHOICE 4\n");
break;
case '5' :
printf("CHOICE 5\n");
break;
case '6' :
printf("CHOICE 6\n");
break;
default :
printf("Choice not found\n");
break;
}
}
printf("you have successfully made out");
return EXIT_SUCCESS;
}

当我运行该程序时,我得到关注。

Welcome to the program.
1. CHOICE 1
2. CHOICE 2
3. CHOICE 3
4. CHOICE 4
5. CHOICE 5
6. Quit
Please enter your choice:
4
You made -1863345812 as your choice
Choice not found
1. CHOICE 1
2. CHOICE 2
3. CHOICE 3
4. CHOICE 4
5. CHOICE 5
6. Quit
Please enter your choice:
2
You made -1863345812 as your choice
Choice not found
1. CHOICE 1
2. CHOICE 2
3. CHOICE 3
4. CHOICE 4
5. CHOICE 5
6. Quit
Please enter your choice:
6
You made -1863345812 as your choice
Choice not found
you have successfully made out

谢谢。

最佳答案

你的代码有两个问题:

首先,如前所述,您正在打印变量 choice 的内存地址,而不是 choice 本身。因此,为此将您的 printf 语句更改为:

printf("You made %d as your choice\n", choice);

其次,您使用错误的 case 进行了切换:您必须使用要匹配的类型,在本例中为 int choice,并且 not a char .因此,将您的案例更改为数字而不是字符:

case 1 : ...

代替

case '1' :...

关于C 程序总是使用 1503657284 或 -1863345812 作为输入的 scanf 选择,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26872157/

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