我有两个函数,我将随机数添加到总值中。
问题是每次我调用该函数并打印总数时,它都没有添加。如果它生成 2,它会说总数是 2。之后如果我再次调用它并且它生成 5,它会说总数是 5,并且不相加(如果发生这种情况应该是 7。)
这里一切看起来都很好......
int human(int humanscore)
{
int diceRoll= rand() % 7;
cout << "player rolled: ";
humanscore+= diceRoll;
cout << diceRoll;
cout << "human score is: " << humanscore;
}
int computer(int compscore)
{
int diceRoll= rand() % 7;
cout << "computer rolled: ";
compscore+= diceRoll;
cout << diceRoll;
cout << "computer score is: " << compscore;
}
最佳答案
您正在修改传递给函数的参数的内部拷贝的值。如果您希望对外部变量进行更改,请将您的函数定义改为采用引用:int& score
。
另请注意,rand() % 7
将为您提供 [0, 6] 范围内的值。骰子的值在 [1, 6] 范围内,您应该改用 1 + rand() % 6
。
* 更新:*
这可以通过 C++ 引用来完成:
int computer(int& compscore)
{
...
compscore += diceRoll;
...
}
int var = 0;
computer( var );
对于此声明,函数将实际变量 var
作为参数,函数内对 compscore
所做的更改反射(reflect)在变量 var
作为 compscore
和 var
用于该特定调用只是同一变量的别名。
在 C 中,使用指针可以达到同样的效果:
int computer(int* compscore)
{
...
*compscore += diceRoll;
...
}
int var = 0;
computer( &var );
该函数的调用为它提供了应更改的变量的地址。对于一般用途,您可以假设第一个使用引用的实现将由编译器自动生成类似于最后一个片段的解决方案。
关于c++ - 添加语句后值没有增加?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7733582/