Data Exchange
Problem Description
问题描述
Write a program, input two integers, are stored in the variables x and y which then use their own definition of swap to swap the values of two variables.
Input formats: Enter only one line, including two integers.
Output Format: Output a single line, are two integers, i.e., after exchange of results.
Requirements: responsible for the main function of the input and output data, but can not directly exchange the values of these two variables, must be done by calling the function defined individually swap, swap the values of the function is only responsible for the exchange of variables, not output the exchange.
输入输出样例
样例输入
4 7
样例输出
7 4
problem analysis
Code
指针方式实现
#include <iostream>
#include <bits/stdc++.h>
using namespace std;
//通过指针完成
void swap(int *x,int *y){
int temp=*x;
*x=*y;
*y=temp;
}
int x,y;
int main(){
cin>>x>>y;
swap(x,y);
cout<<x<<" "<<y;
return 0;
}
地址引用方式实现
#include <iostream>
#include <bits/stdc++.h>
using namespace std;
//地址引用方式
void swap(int &x,int &y){
int temp=x;
x=y;
y=temp;
}
int x,y;
int main(){
cin>>x>>y;
swap(x,y);
cout<<x<<" "<<y;
return 0;
}
operation result
5 4
4 5
--------------------------------
Process exited after 2.646 seconds with return value 0
请按任意键继续. . .
to sum up
Exchange of data, the exchange value is, by this question requires a custom function not directly exchange the values of two functions in the main function, the fetching pointer using the reference address form or in the form of exchange, so that exchange two variables values changed