gpt4 book ai didi

c - 为什么相同的变量打印不同的输出?

转载 作者:行者123 更新时间:2023-12-02 06:31:17 26 4
gpt4 key购买 nike

#include <stdlib.h>
#include <stdio.h>
void roll_three(int* one, int* two, int* three)
{

int x,y,z;
x = rand()%6+1;
y = rand()%6+1;
z = rand()%6+1;

one = &x;
two = &y;
three = &z;
printf("%d %d %d\n", *one,*two,*three);
}
int main()
{
int seed;
printf("Enter Seed: ");
scanf("%d", &seed);
srand(seed);
int x,y,z;
roll_three(&x,&y,&z);
printf("pai: %d %d %d\n", x,y,z);
if((x==y)&&(y==z))
printf("%d %d %d Triple!\n",x,y,z);
else if((x==y)||(y==z)||(x==z))
printf("%d %d %d Double!\n",x,y,z);
else
printf("%d %d %d\n",x,y,z);
return 0;

}

这是终端,我输入 123 作为种子。但是,roll_three 中的 printf 和 main 中的 printf 给我不同的输出?为什么 *one 和 x 不同?

最佳答案

问题出在这里:

one = &x;
two = &y;
three = &z;

由于 onetwothree 是指针,您已经更改了它们指向的内容,但现在它们不再指向 mainxyz。类似于这个...

void foo(int input) {
input = 6;
}

int num = 10;
foo(num);
printf("%d\n", num); // it will be 10, not 6.

相反,您想更改存储在它们指向的内存中的值。因此取消对它们的引用并为它们分配新值。

*one = x;
*two = y;
*three = z;

您甚至可以消除中间值。

*one   = rand()%6+1;
*two = rand()%6+1;
*three = rand()%6+1;

关于c - 为什么相同的变量打印不同的输出?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35662972/

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