我使用 4 和 5 作为输入。算术:
a' = 4+5
b'= |4-5|
这个问题是,当执行减法语句时,“a”被读取为 9 而不是 4。我想使用参数中传递的原始用户输入“a”(即 4)而不是“新 a”(即 9)。
void update(int *a, int *b)
{
// Function will add and subtract updating the integers
*a = *a + *b; //4+5=9 is stored in *a
*b = abs(*a - *b); //*a is still 9 but needs to be original value of 4
//This should be |4-5|=1
}
int main()
{
int a, b;
int *pa = &a, *pb = &b;
scanf("%d %d", &a, &b);
//Implementation
update(pa, pb);
printf("%d\n%d", a, b); // this output should be 9 and 1
return 0;
}
最佳答案
使用临时变量来帮助计算。
void update(int *a, int *b)
{
int temp = *a;
*a = temp + *b;
*b = abs(temp - *b);
}
由于您使用的是 C++,因此我建议使用引用类型作为参数。
void update(int& a, int& b)
{
int temp = a;
a = temp + b;
b = abs(temp - b);
}
并将其用作:
update(a, b);
关于c++ - 如何使用参数中传递的初始值而不是更新后的值进行后续计算?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49594409/