无法找出 Java 等效的 "passing by reference" 在C++解决这个问题,以及最好的解决方法



我参加了C++的CS-1课程,现在我在一所新大学,他们在这里使用Java。我一直在学习新语法,做我以前的C++实验室,我遇到了一个通过参考的问题。

到目前为止,我的理解是Java是通过价值传递的,但我如何才能实现这个问题的目标?

编写一个程序,告诉从1美分到497美分的任何金额的零钱都要分发什么硬币。由于我们不会用便士,我们需要将任何一美分四舍五入到接近5或10。例如,如果金额为368美分,则四舍五入的数字为370美分;如果金额为367美分,那么四舍五进的数字为365美分。零钱是1个toonie(两美元硬币),1个loonie,2个25美分,2个1角硬币兑换370美分。使用面额为2美元(toonie)、1美元(loonie)、25美分(25美分)、10美分(1角硬币)和5美分(5美分硬币)的硬币。您的程序将使用以下功能:

Void computeCoin(int coinValue, int &number, int &amountLeft);

请注意,此函数需要返回两个值,因此必须使用引用变量。

例如,假设变量amountLeft的值为370美分。然后,在下面的调用之后,number的值将是1,amountLeft的值将为170(因为如果你从370美分中取1个toonie,就剩下170美分):

computeCoin(200, number, amountLeft);

在您拨打以下电话之前,打印带有硬币名称的数字值:

computeCoin(100, number, amountLeft);

包括一个循环,让用户对新的输入值重复此计算,直到用户输入哨兵值以停止程序。

在C++中,我可以只使用参考变量,硬币的价值可以更改。到目前为止,我学到的是对象是使用引用的一种方式,我不知道如何真正做到这一点,也不知道是否有更好的方法。我在这里包含了C++代码:

#include <iostream>
using namespace std; 
void computeCoin(int coinValue, int & number, int & amountLeft);
int main()
{
int number, change, amountLeft, remainder;
do
{
cout << "Enter the change (-1 to end): ";
cin >> change;
while (change>497)
{
cout << "The change should be less than 497. Try again.nn";
cout << "Enter the change (-1 to end): ";
cin >> change;
}
if (change != -1)
{
// round to near 5 or 10's
remainder = change % 5;
if (remainder <= 2)
amountLeft = change - remainder; 
else
amountLeft = change + 5 - remainder;
if (amountLeft == 0)
cout << "No change.";
else
{
cout << amountLeft << " cents can be given asn";
// compute the number of toonies
computeCoin(200, number, amountLeft);
if (number>0)
cout << number << " toonie(s)  ";
// compute the number of loonies
computeCoin(100, number, amountLeft);
if (number>0)
cout << number << " loonie(s)  ";
// compute the number of quarters
computeCoin(25, number, amountLeft);
if (number>0)
cout << number << " quarter(s)  ";
// compute the number of dimes
computeCoin(10, number, amountLeft);
if (number>0)
cout << number << " dime(s)  ";
// compute the number of nickels
computeCoin(5, number, amountLeft);
if (number>0)
cout << number << " nickel(s)  ";
}
cout << endl << endl;
}
} while (change != -1);

cout << "nGoodbyen";
return 0;
}
void computeCoin(int coinValue, int &number, int &amountLeft)
{
number = amountLeft / coinValue;
amountLeft %= coinValue;
}

您可以(也可能应该)返回一个对象作为Joop Eggen在注释中指出的结果。

一种有时有效的替代方法(从技术上讲,它总是有效的,但不应该总是使用)是传递一个可变对象,如下所示:

class MutableInteger
{
private int value;
public void setValue(final int val)
{
value = val;
}
public int getValue()
{
return value;
}
}

然后将其实例而不是int参数传递到方法中。

基本上,这就像C中的一个结构。不过,我还是建议在这种特定情况下返回一个结果。

最新更新