1. Simple assignment expression
#include <stdio.h>
#include <math.h>
int main()
{
int a, b;
a = 3;
double c, d;
b = a * a;
c = 3.75;
d = sin(b) + 1;
}
2. Automatic conversion of data type during assignment
Left value | Right value | Conversion method | For example |
---|---|---|---|
Integer variable | Floating point data | Floating point numbers discard the decimal part | int a=4.38; |
Floating-point variable | Integer data | The value is unchanged and stored in exponential form | double=375; |
float variable | double data | Decreased accuracy, possible overflow | float f=2.8e59 |
unsigned variable | Signed data of the same length | Copy as it is, but the original sign bit is also treated as the value part | unsigned int u=-32765; |
#include <stdio.h>
int main()
{
int i = 3.123456789;
double d = 3;
float f = 3.123456789123456789;
unsigned u1 = 1234;
unsigned u2 = -1234;
printf("i=%d\n", i);
printf("d=%f\n", d);
printf("f=%f\n", f);
printf("u1=%u\n", u1);
printf("u2=%u\n", u2);
}
输出结果及解析:
i=3 /舍弃小数部分
d=3.000000 /整数转为小数存储和输出
f=3.123457 /精度降低
u1=1234 /值未变
u2=4294966062 /符号位当数值处理
Three. Compound assignment operator
#include <stdio.h>
int main()
{
int a = 9;
a += 3; printf("%d\n", a); a = 9;
a -= 3; printf("%d\n", a); a = 9;
a *= 3; printf("%d\n", a); a = 9;
a /= 3; printf("%d\n", a); a = 9;
a %= 3; printf("%d\n", a); a = 9;
}
输出结果:
12
6
27
3
0
Advantages of compound assignment operator
① simplify the program
② improve efficiency
4. Assignment expression and its value
Assignment statement:
a=3;
b+=6.32;
assignment expression:
a=3
b+=6.32
#include <stdio.h>
int main()
{
int a, b, c;
printf("%d\n", (a = 5));
printf("%d\n", (b = (c = 6)));
printf("%d %d %d\n", a, b, c);
}
5
6
5 6 6
Five. Assignment expression evaluation
Combination method: from right to left
a=(b=5)
a=b=c=5
a=5+(c=6)
a%=(n%=2)
printf("%d",(j=i++));
(a=3*5)=4*3
a+=a-=a*a