蓝桥杯ALGO-221 算法训练 数据交换
问题描述
编写一个程序,输入两个整数,分别存放在变量x和y当中,然后使用自己定义的函数swap来交换这两个变量的值。
输入格式:输入只有一行,包括两个整数。
输出格式:输出只有一行,也是两个整数,即交换以后的结果。
要求:主函数负责数据的输入与输出,但不能直接交换这两个变量的值,必须通过调用单独定义的函数swap来完成,而swap函数只负责交换变量的值,不能输出交换后的结果。
输入输出样例
样例输入
4 7
样例输出
7 4
很简单一道题,迅速完成
#include <iostream>
#include <bits/stdc++.h>
using namespace std;
/* run this program using the console pauser or add your own getch, system("pause") or input loop */
void swap(int a, int b){
int temp;
temp = a;
a = b;
b = temp;
}
int main(int argc, char** argv) {
int x, y;
cin >> x >> y;
swap(x, y);
cout << x << " " << y;
return 0;
}
不太行,并没有交换,所以我在函数里输出了一遍,发现函数里交换是对的
那么从根源找问题,换地址
#include <iostream>
#include <bits/stdc++.h>
using namespace std;
/* run this program using the console pauser or add your own getch, system("pause") or input loop */
void swap(int *a, int *b){
int *temp;
temp = a;
a = b;
b = temp;
}
int main(int argc, char** argv) {
int x, y;
cin >> x >> y;
swap(x, y);
cout << x << " " << y;
return 0;
}
用指针解决
成功
话说还得找找指针的视频看看,都忘了