注册 登录
编程论坛 C++教室

我写了一个程序,大家帮我看看哪里有问题

wuzihao 发布于 2008-06-04 11:36, 796 次点击
// test5.4.cpp : demonstrates passing by value

#include "stdafx.h"
#include "iostream"

using namespace std;
void swap(int x, int y);

int main()
{
    int x = 5,y = 10;

    cout <<"Main.Before swap, x: "<< x <<" y: "<< y << endl;
    swap(x,y);
    cout <<"Main.After swap, x: "<< x <<" y: "<< y << endl;
    return 0;
}

void swap(int x, int y)
{
    int temp;

    cout <<"Swap.Before swap,x: "<< x <<" y: "<< y << endl;

    temp = x;
    x = y;
    y = temp;

    cout <<"Swap.After swap,x: "<< x <<" y: "<< y << endl;
}
7 回复
#2
zzy8402082008-06-04 12:21
包含的头文件有问题
#include "stdafx.h" 不需要用这个;
#include "iostream" 改为#include<iostream> 因为这是库里面的,而不是你自己定义的.
#3
sjz_zdf2008-06-22 18:52
交换值能实现吗?swap()函数中的形式参数用引用比较好吧,呵呵~~~
#4
kongwei2542008-06-23 17:24
什么问题都没有
如果不能运行可能是编译器有问题
#5
守鹤2008-06-23 18:31
这肯定不能交换数据啊
1.不需要#include "stdafx.h"
子函数改成一下就行了

void swap(int &x, int &y)
{
    int temp;

    cout <<"Swap.Before swap,x: "<< x <<" y: "<< y << endl;

    temp = x;
    x = y;
    y = temp;

    cout <<"Swap.After swap,x: "<< x <<" y: "<< y << endl;
}
#6
kongwei2542008-06-26 16:57
楼上的看清人家的意图好不好!!
#7
雪城白鸟2008-06-26 18:52
误区
你没有弄清楚什么是按值传递和按引用传递,再看下书
#8
ja8608252008-06-26 21:53
#include "iostream"

using namespace std;
void swap(int *, int *);

int main()
{
    int x = 5,y = 10;

    cout <<"Main.Before swap, x: "<< x <<" y: "<< y << endl;
    swap(&x,&y);
    cout <<"Main.After swap, x: "<< x <<" y: "<< y << endl;
    return 0;
}

void swap(int *x, int *y)
{
    int temp;

    cout <<"Swap.Before swap,x: "<< *x <<" y: "<< *y << endl;

    temp = *x;
    *x = *y;
    *y = temp;

    cout <<"Swap.After swap,x: "<< *x <<" y: "<< *y << endl;
}
1