号码交换:如何让这个程序的主要功能调用参考功能?
Number swapping: How do I get this program's main function to call the reference function?
所以我有这个程序,它可以交换用户输入的两个数字,唯一的问题是我无法让主函数调用进行交换的函数,代码如下:
#include <iostream>
using namespace std;
float first,
second;
void swap(float first, float second);
int main()
{
// Prompt user to enter the first number.
cout << "Enter the first number" << endl;
cout << "Then hit enter" << endl;
cin >> first;
// Prompt user to enter the second number.
cout << "Enter the second number" << endl;
cout << "Then hit enter" << endl;
cin >> second;
// Echo print the input.
cout << endl << "You input the numbers as " << first
<< " and " << second << endl;
swap(first, second);
return 0;
}
void swap(float &number1, float &number2)
{
number1 = number2;
number2 = number1;
// Output the values.
cout << "After swapping, the values of the two numbers are "
<< number1 << " and " << number2 << endl;
}
在您的函数声明中,您有 first
和 second
按值传递:
void swap(float first, float second);
这需要通过引用传递,如函数定义中所给:
void swap(float &number1, float &number2);
提醒一下,您会注意到当您 运行 它会打印出 number2 两次。当您交换值时,您需要第三个(临时)变量。
void swap(float &number1, float &number2)
{
float temp = number1;
number1 = number2;
number2 = temp; // We change this to temp because you already changed number1 to
// equal number2. If we set number2 = number1, we'd just end up
// with the value we started with for number2.
// Output the values.
cout << "After swapping, the values of the two numbers are "
<< number1 << " and " << number2 << endl;
}
希望对您有所帮助!祝你好运 class
所以我有这个程序,它可以交换用户输入的两个数字,唯一的问题是我无法让主函数调用进行交换的函数,代码如下:
#include <iostream>
using namespace std;
float first,
second;
void swap(float first, float second);
int main()
{
// Prompt user to enter the first number.
cout << "Enter the first number" << endl;
cout << "Then hit enter" << endl;
cin >> first;
// Prompt user to enter the second number.
cout << "Enter the second number" << endl;
cout << "Then hit enter" << endl;
cin >> second;
// Echo print the input.
cout << endl << "You input the numbers as " << first
<< " and " << second << endl;
swap(first, second);
return 0;
}
void swap(float &number1, float &number2)
{
number1 = number2;
number2 = number1;
// Output the values.
cout << "After swapping, the values of the two numbers are "
<< number1 << " and " << number2 << endl;
}
在您的函数声明中,您有 first
和 second
按值传递:
void swap(float first, float second);
这需要通过引用传递,如函数定义中所给:
void swap(float &number1, float &number2);
提醒一下,您会注意到当您 运行 它会打印出 number2 两次。当您交换值时,您需要第三个(临时)变量。
void swap(float &number1, float &number2)
{
float temp = number1;
number1 = number2;
number2 = temp; // We change this to temp because you already changed number1 to
// equal number2. If we set number2 = number1, we'd just end up
// with the value we started with for number2.
// Output the values.
cout << "After swapping, the values of the two numbers are "
<< number1 << " and " << number2 << endl;
}
希望对您有所帮助!祝你好运 class