由于某种原因,这会返回原始值,有人能告诉我原因吗?谢谢!我设置了temp,不确定这是否正确,因为num1和num2需要设置为相等,如果我没有,它们都会保持1个值。
代码:
#include <iostream>
using namespace std;
void swap1(double& num1, double& num2);
void swap2(double& num1, double& num2);
double num1, num2;
int main(){
cout << "Give me two numbers to swap: ";
cin >> num1 >> num2;
cout << "Original: " << num1 << ", " << num2 << endl;
void swap1(double& num1, double& num2);
cout << "First swap: " << num1 << ", " << num2 << endl;
void swap2(double& num1, double& num2);
cout << "Second swap: " << num1 << ", " << num2 << endl;
}
void swap1(double& num1, double& num2){
double temp1;
temp1 = num1;
num1 = num2;
num2 = temp1;
}
void swap2 (double& num1, double& num2){
double temp2;
temp2 = num1;
num1 = num2;
num2 = temp2;
}
输出:抱歉格式错误!
Running /home/ubuntu/workspace/ASSIGN#31.cpp
Give me two numbers to swap: 10 20
Original: 10, 20
First swap: 10, 20
Second swap: 10, 20
答案 0 :(得分:1)
cout << "Original: " << num1 << ", " << num2 << endl; void swap1(double& num1, double& num2);
这不会调用swap1
。它是(重新)声明,而不是函数调用。请改用:
swap1(num1, num2);
答案 1 :(得分:1)
变化:
void swap1(double& num1, double& num2);
void swap2(double& num1, double& num2);
在您的主要功能中:
swap1(num1, num2);
swap2(num1, num2);
它应该可以工作,因为你正在使用一个函数,而不是在你的主函数中声明它。