题目1代码:
#include <iostream>
using namespace std;
int main()
{
float a,b,tmp;
cout << "请输入a 和b的值:"<< endl;
cin >> a >> b;
{
tmp = a;
a = b;
b = tmp;
}
cout << "交换后a=" << a << ",b=" << b <<endl;
return 0;
}
题目2代码:
#include <iostream>
using namespace std;
float a,b; //全局变量
void exchange(float a,float b)
{
float tmp;
tmp = a;
a = b;
b = tmp;
}
int main()
{
cout << "请输入a 和b的值:"<< endl;
cin >> a >> b;
exchange(a,b);
cout << "交换后a=" << a << ",b=" << b <<endl;
return 0;
}
题目3代码:
#include <iostream>
using namespace std;
void exchange(float *a,float *b)
{
float tmp;
tmp = (*a);
*a = *b;
*b = tmp;
}
int main()
{
float a,b;
cout << "请输入a 和b的值:"<< endl;
cin >> a >> b;
exchange(&a,&b);
cout << "交换后a=" << a << ",b=" << b <<endl;
return 0;
}
第一种是没有交换的,因为只是改变了形参
void swap(int *x,int *y)
{
int *t;
t=x;
x=y;
y=t;
}
第二种是可以的
void swap(int *x,int*y)
{
int t;
t=*x;
*x=*y;
*y=t;
}
第三种会出现故障,无法正常运行,原因是指针变量没有分配空间
void swap(int *x,int*y)
{
int *t;
*t=*x;
*x=*y;
*y=*t;
}
int main(){
int q=1;int w=2;
swap(&q,&w);
cout<<q<<w;
return 0;
}
您好,我是有问必答小助手,您的问题已经有小伙伴解答了,您看下是否解决,可以追评进行沟通哦~
如果有您比较满意的答案 / 帮您提供解决思路的答案,可以点击【采纳】按钮,给回答的小伙伴一些鼓励哦~~
ps:问答VIP仅需29元,即可享受5次/月 有问必答服务,了解详情>>>https://vip.csdn.net/askvip?utm_source=1146287632