C-赋值运算符
时间:2020-02-23 14:31:52 来源:igfitidea点击:
在本教程中,我们将学习C编程语言中的赋值运算符。
我们使用赋值运算符将表达式的结果赋给变量。
在下面的示例中,我们将整数值10分配给数据类型为integer的可变分数。
int score = 10;
速记分配运算符
假设我们有一个整数变量,并且最初已为其分配了10。
然后说我们将值增加5并为其分配新值。
//declare and set value int x = 10; //increase the value by 5 and re-assign x = x + 5;
编写代码" x = x + 5"的另一种方法是使用速记赋值" + =",如下所示。
//declare and set value int x = 10; //increase the value by 5 and re-assign x += 5;
以下是速记赋值运算符的列表。
| 简单赋值 | 速记赋值 |
|---|---|
| x = x + 1 | x + = 1 |
| x = x-1 | x-= 1 |
| x = x *(n + 1) | x * =(n + 1) |
| x = x /(n + 1) | x/=(n + 1) |
| x = x%y | x%= y |
在以下示例中,我们从用户获取值x,然后从用户获取新值y。
然后,我们将y添加到x并将结果分配给x。
最后,我们将打印存储在变量x中的新值。
#include <stdio.h>
int main(void)
{
int x, y;
printf("Enter the value of x: ");
scanf("%d", &x);
printf("Enter the value of y: ");
scanf("%d", &y);
//add y to x and re-assign
x = x + y;
printf("New value of x: %d\n", x);
return 0;
}
Enter the value of x: 10 Enter the value of y: 20 New value of x: 30
将x添加到y并将新值重新分配给x的另一种方法是使用速记赋值运算符" + ="。
#include <stdio.h>
int main(void)
{
int x, y;
printf("Enter the value of x: ");
scanf("%d", &x);
printf("Enter the value of y: ");
scanf("%d", &y);
//add y to x and re-assign
x += y;
printf("New value of x: %d\n", x);
return 0;
}

