gpt4 book ai didi

c - Scanf 和地址运算符 (&) 在 for 循环内不起作用

转载 作者:太空宇宙 更新时间:2023-11-03 23:38:24 25 4
gpt4 key购买 nike

我有一个任务,我想知道为什么当我编译并运行这段代码时,scanf("%d", &temp_pin) 没有将数据存储在地址中。我知道这一点,因为在 printf("%d", temp_pin) 的下一条语句中,我只获得了随机变量。我在前面的代码行中有另一个 scanf 语句可以工作,但我很困惑为什么这个语句不起作用。非常感谢!

#include <stdio.h>

int main()
{
//Deceleration of Variables
int option;
int pin [4]={1, 2, 3, 4};
int temp_pin [4];
int new_pin [4];
int temp_new_pin [4];
int correct;
int incorrect;



do
{
printf("Please enter which option you wish to operate\n\n");
printf("1. Enter your pin\n");
printf("2. Change your pin\n");
printf("3. Display the number of times the PIN was entered: \n Successfully\n Unsuccessfully\n");
printf("4. Exit Program\n\n");

scanf("%d", &option);

if (option == 1)
{
printf("\nPlease Enter Your PIN\n");

for (int i = 0; i < 4; i++)
{
scanf(" %d", &temp_pin);
printf(" %d", temp_pin);

if (temp_pin==pin)
{
printf("\nYour PIN is correct\n");
}

if (temp_pin != pin)
{
printf("\nYour PIN is incorrect\n");
}
}//End For
}//End If

} // end do
while(option != 4);

return 0;
}

最佳答案

如果我能提出一个建议,那就是将所有整数数组更改为整数。这将解决您所有的问题。但是,如果您的作业需要使用整数数组,请遵循以下代码。

目前您仅将 temp_pin 的第一个元素设置为等于用户输入。 scanf("%d", &temp_pin); 行实际上将一个整数存储到 temp_pin[0] 中。

由于引脚大小为 4,因此您需要读入 4 个单独的整数以存储在数组中。我建议使用可以设置 temp_pin[0]、temp_pin[1]、temp_pin[2]、temp_pin[3]

值的 for 循环

从逻辑上讲,我还建议对每个整数进行错误检查,因为整数的大小可以从 -32,768 到 32,767。目前,包含元素 3300,55,12,15 的整数数组将是一个有效的 pin。

您在此行 printf("%d", temp_pin); 中给出的值不是随机变量。这是临时引脚的地址。为了打印存储在 temp_pin 中的值,您需要遍历数组中的每个元素并单独打印它。

对于您的比较语句 if (temp_pin==pin),这永远不会导致 true,因为它正在比较地址。同样,正确的解决方法是同时遍历两个列表并比较每个元素。

关于c - Scanf 和地址运算符 (&) 在 for 循环内不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53072182/

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