为什么自定函数没有起作用?

发布时间:2024-05-14 03:30 发布:上海旅游网

问题描述:

自定了排序函数sorth,为什么无法正确显示呢?我调试过函数确实起作用,VC也显示无错误,就是无法改变main()函数中的值
程序如下:
#include<iostream>
using namespace std;
void sorth(int m1,int m2)
{
int temp;
if(m1>m2)
{
temp=m1;
m1=m2;
m2=temp;
}
}
void main()
{
int a,b,c;
cout<<"please input 3 numbers"<<endl;
cin>>a>>b>>c;
sorth(a,b);
sorth(a,c);
sorth(b,c);
cout<<"the sorth is "<<a<<","<<b<<","<<c<<endl;
}

问题解答:

void sorth(int m1,int m2)
你这是传值的方式,所以,不能把函数中运算的结果传递到函数外面去

要用引用的(或传地址)方式,如下:

#include<iostream>
using namespace std;

void sorth(int &m1,int &m2) //void sorth(int m1,int m2)
{
int temp;
if(m1>m2)
{
temp=m1;
m1=m2;
m2=temp;
}
}
void main()
{
int a,b,c;
cout<<"please input 3 numbers"<<endl;
cin>>a>>b>>c;
sorth(a,b);
sorth(a,c);
sorth(b,c);
cout<<"the sorth is "<<a<<","<<b<<","<<c<<endl;
}

你所用的形参无法进行传递,值传递只能在函数内部进行改变,只负责传值,无法改变原值,所以不行,你最好换成引用或者指针的形式

是返回值的问题,用指针做吧。
#include<iostream>
using namespace std;
void sorth(int *p,int *q)
{
int temp;
if(*p>*q)
{
temp=*q;
*q=*p;
*p=temp;
}
}
void main()
{
int a,b,c,*p,*q,*l;
cout<<"please input 3 numbers"<<endl;
cin>>a>>b>>c;
p=&a;q=&b;l=&c;
sorth(p,q);
sorth(p,l);
sorth(q,l);
cout<<"the sorth is "<<*p<<","<<*q<<","<<*l<<endl;
}

热点新闻