c++ - 如何使用参数中传递的初始值而不是更新后的值进行后续计算?

标签 c++ pointers visual-c++

我使用 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/

相关文章:

.net - 如何将 System::String^ 转换为 std::string?

c++ - Qt 5 : update QProgressBar during QThread work via signal

c++ - 函数指针?

c++ - 如何安全地将 new 创建的对象传递给构造函数

C 程序在尝试使用指针访问字符串数据时不打印文本

visual-studio-2008 - 在构建期间复制文件

c++ - 跟踪过程直到完成

c++ - 以char 'e'为输入进行比较

c++ - 尝试访问存储在 vector 中的数据时出现段错误

c++ - 与 GCC/MSVC 中的 lambda 转换构造函数不一致