简体   繁体   English

我对输出感到困惑

[英]I'm confused about the output

#include <stdio.h>
#include <stdlib.h>

int main()
{
  int a , b ,c ;
  printf("Enter values for a and b: ");
  scanf("%d%d",&a,&b);

    a = a + b-- ;

  if (a<b){
    c = -1;
  printf("\n\t%d %d %d\n\n",a,b,c);
          }
  else {
    c = 0;
    printf("\n\t%d %d %d\n\n",a,b,c);
       }
}

Lets assume the value of the input for a and b are 2 (for both of them).让我们假设 a 和 b 的输入值为 2(对于它们两者)。
I studied the above program, but when it comes to the output it will be 4 1 0, a=4,b=1,c=0.我研究了上面的程序,但是当涉及到输出时,它将是 4 1 0, a=4,b=1,c=0。 But, the calculation part above said that a=a+b-1 which will be the value of a is 3, now the new value of a is 3. But for b the value is still 2 because we didn't assign a new value to it.但是,上面的计算部分说 a=a+b-1 这将是 a 的值是 3,现在 a 的新值是 3。但是对于 b,值仍然是 2,因为我们没有分配一个新的对它的价值。

I am very confused about the output.我对输出感到非常困惑。

There is a difference between a+1 , a++ and ++a . a+1a++++a之间存在差异。 Details here .详情请看这里 Therefore, when you say因此,当你说

a = a + b--;

You are actually saying你实际上是在说

a = a + b;
b = b - 1;

If you say如果你说

a = a + --b;

It becomes它成为了

b = b - 1;
a = a + b;

And if you say如果你说

a = a + (b-1)

It does what you think: a = a + b - 1 .它按照您的想法执行: a = a + b - 1 The value of b doesn't change afterwards. b的值之后不会改变。

At the beginning, a and b are both 2一开始,a和b都是2

Then, you execute a = a + b--;然后,你执行a = a + b--; . .

The decrement operator is located after the b , so it evaluates to:递减运算符位于b ,因此其计算结果为:

a=a+b;
b=b-1;

After this, a will be 4 and b will be 1.在此之后,a 将为 4,b 将为 1。

a is not smaller than b, so c will be 0. a 不小于 b,所以 c 将为 0。

Note:笔记:

If it would be a = a + --b , it would evaluate to如果它是a = a + --b ,它将评估为

b=b-1;
a=a+b;

Because the -- is executed at the beginning of the evaluation.因为--是在评估开始时执行的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM