我使用4和5作为我的输入。算术:
a‘= 4+5
b'= |4-5|
这个问题是,当执行减法语句时,"a“被读入为9而不是4。我想使用在参数中传递的原始用户输入"a“(即4),而不是"new 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;
}发布于 2018-04-01 11:08:32
使用临时变量来帮助计算。
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);发布于 2018-04-01 11:17:10
引用比指针要酷得多。C++比C要酷得多,所以就用iostream吧。尝试使用描述性名称。当张贴问题时,不要忘记头文件。
#include <iostream>
#include <cmath>
void update(int &a, int &b)
{
int sum = a+b;
b = abs(a - b);
a = sum;
}
int main() {
int a {4};
int b {5};
update(a, b);
std::cout << a << ' ' << b << '\n';
return 0;
}发布于 2018-04-01 12:01:47
您应该使用temp变量,并且代码应该是优化的。您不需要声明int *pa = &a,*pb = &b;这些变量,而是使用引用&。以下代码是您的代码的最佳解决方案。
void update(int& a, int& b)
{
int temp = a;
// Function will add and subtract updating the integers
a = a + b; //4+5=9 is stored in *a
b = abs(temp - b); //*a is still 9 but needs to be original value of 4
//This should be |4-5|=1
}
int main()
{
int a, b;
scanf("%d %d", &a, &b);
//Implementation
update(a, b);
printf("%d\n%d", a, b); // this output should be 9 and 1
return 0;
}https://stackoverflow.com/questions/49594409
复制相似问题