gpt4 book ai didi

c++ - 在 C++ 中使用指针在 3 个变量之间旋转值

转载 作者:行者123 更新时间:2023-11-27 23:01:46 24 4
gpt4 key购买 nike

我有以下代码:

int main(){
int a,b,c;
cout<<"Enter a: ";
cin>>a;
cout<<"Enter b: ";
cin>>b;
cout<<"Enter c: ";
cin>>c;
int temp;
int *aPtr = &a, *bPtr = &b, *cPtr = &c;
int *tempPtr = &temp;
*tempPtr = *aPtr;
*aPtr = *bPtr;
*bPtr = *cPtr;
*cPtr = *tempPtr;
cout<<a<<b<<c<<"\n";
system("pause");
return 0;
}

输入:

2 3 4

输出

3 4 2

预期输出

4 2 3

我正在使用相同的交换值逻辑。我究竟做错了什么?

谢谢!

最佳答案

您将根据您编写的代码获得输出。在这种情况下正确的轮换逻辑是:-

int temp;
int *aPtr = &a, *bPtr = &b, *cPtr = &c;
int *tempPtr = &temp;
*tempPtr = *cPtr;
*cPtr = *bPtr;
*bPtr = *aPtr;
*aPtr = *tempPtr;

按顺序走就行了。就像先存储 c 的值然后移动 a 和 b 然后恢复 a 这样您就可以很容易地概括这一点。

关于c++ - 在 C++ 中使用指针在 3 个变量之间旋转值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26840451/

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