wuzihao 发表于 2008-6-4 11:36

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

// 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;
}

zzy840208 发表于 2008-6-4 12:21

包含的头文件有问题

#include "stdafx.h" 不需要用这个;
#include "iostream" 改为#include<iostream> 因为这是库里面的,而不是你自己定义的.

sjz_zdf 发表于 2008-6-22 18:52

交换值能实现吗?swap()函数中的形式参数用引用比较好吧,呵呵~~~

kongwei254 发表于 2008-6-23 17:24

什么问题都没有
如果不能运行可能是编译器有问题

守鹤 发表于 2008-6-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;
}

kongwei254 发表于 2008-6-26 16:57

楼上的看清人家的意图好不好!!

雪城白鸟 发表于 2008-6-26 18:52

误区

你没有弄清楚什么是按值传递和按引用传递,再看下书

ja860825 发表于 2008-6-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]

编程论坛