2017-08-15 144 views
0

如何在此代码中更改x和y的值?x和y的交换值

当我试图通过x=y, y=x;它将它更改为相同的数字。

我该怎么做?

我该如何做3个值,如(xyz)?

#include <iostream> 
using namespace std; 
int main() 
{ 
    int x=4; 
    int y=6; 
    cout<<x<<y; 
    return 0; 
} 

我以前试过这个代码,但它不能按我想要的方式工作。

#include <iostream> 
using namespace std; 
int main() 
{ 
    int x=4; 
    int y=6; 
    x=y,y=x; 
    cout<<x<<y; 
    return 0; 
} 
+1

这个词是“交换”。你会得到相当不错的谷歌结果。 – LogicStuff

+1

C++标准库附带了许多不错的[algorithm](http://en.cppreference.com/w/cpp/algorithm)和[utility](http://en.cppreference.com/w/cpp/utility)功能。 –

回答

2

这是因为你第一次x的值,然后该值复制到y。有一个称为std::swap的标准库函数,它应该完成这项工作。

你可以看到它的一个缩写here

std::swap在C++ 11之前的标题<algorithm>和自C++ 11以来的<utility>中定义。所以请确保你的#include正确的标题。

在C++ 11中使用std::swap而不是将值复制到第三个临时变量的好处是,std::swap使用std::move,因此不会创建其他副本。


为三个数字,你将不得不作出自己的实现是这样的:

#include <iostream> 

int main() { 
    int x{5}, y{3}, z{2}; 

    int temp{std::move(x)}; 
    x = std::move(y); 
    y = std::move(z); 
    z = std::move(temp); 

    std::cout << x << ' ' << y << ' ' << z << '\n'; 

    return 0; 

} 

Ideone

0

试试这个:

#include <iostream> 
using namespace std; 
int main() 
{ 
    int x=4; 
    int y=6; 

    int temp=x; 
    x=y; 
    y=temp; 
    cout<<x<<y; 
    return 0; 
} 
0
x=4 
y=6 

x=y // x=6, y=6 

y=x // does nothing 

尝试使用其他变量:

#include <iostream> 
using namespace std; 
int main() 
{ 
    int x=4; 
    int y=6; 
    int temp=x; 
    x=y,y=temp; 
    cout<<x<<y; 
    return 0; 
} 
+3

请(学习)使用编辑器的格式选项。 – Scheff

+0

您可以使用[编辑]链接改进您的答案。 – Scheff

+0

感谢您的评论,我会在这个更好,我希望。 –

0

,不使用第三个变量,你可以做交换两个变量这样,

#include <iostream> 
using namespace std; 
int main() 
{ 
    int x=4; 
    int y=6; 

    x = x + y; 
    y = x - y; 
    x = x - y; 
    cout<<"X = "<<x << "\n" 
     <<"Y = "<<y; 
    return 0; 
} 

所以输出将是,

X = 6

Y = 4

1

有两个选项:

  1. 介绍临时变量:

    INT临时= Y; y = x; x =临时;

  2. 或者使用std ::这样std::swap(x, y);交换(您可能需要进口<algorithm><utility>

现在为什么你收到此错误?让我们一步一步分析你在做什么:

  1. x = y;给出y的x值。所以现在x等于y
  2. y = x;给出x的y值。但是等等,x现在等于y。所以没有改变。

如果你仍然无法理解你做错了什么,我建议你一张纸然后按照你自己的代码一步一步写在每一步写程序的状态。

作为未来建议的最后一件事。请让您的问题清晰并格式正确。例如,它完全不理解你的观点与3个值。请解释你的意思,并可能提供一些例子,然后也许有人能够帮助你。

2

对于2个变量,应使用std::swap,对于更多的变量,可以使用std::tuple

std::tie(x, y, z) = std::make_tuple(y, z, x); 

Demo

+0

我认为你链接了错误的演示? –

+0

另外,我相信'std :: tie(x,y,z)= {y,z,x};'已经足够了 –

+0

@ M.M:Demo fixed。 – Jarod42

0

这里被码交换2个变量(1行)

#include <iostream> 
using namespace std; 
int main() 
{ 
    int x = 4; 
    int y = 6; 
    cout << x<< y; 
    swap(x,y); 
    cout << x << y; 
    getchar(); 
    return 0; 
} 

这里是交换3个变量的代码(1行)

#include <iostream> 
#include <tuple> 
using namespace std; 
int main() 
{ 
    int x = 4; 
    int y = 6; 
    int z = 8; 
    cout << x<< y<<z; 
    tie(x, y, z) = make_tuple(y, z, x); 
    cout << x << y << z; 
    getchar(); 
    return 0; 
} 
+0

已经有很多答案。你也定义了z,但不要使用它。解释你的答案与其他答案是不同的? – Nic3500

+0

我在定义变量z时定义了与3变量交换时,我忘记删除它。我的答案是不同的,因为它只涉及一行代码。 – Eitan