將 1 新增到給定數字?
將 1 新增到給定數字的程式透過 1 增加變數的值。這通常用於計數器。
有 2 種方式可用於將給定數字增加 1 −
將 1 簡單地新增到數字並將其重新分配給變數。
在程式中使用增量運算子。
方法 1 − 使用重新分配方法
此方法獲取變數,向其新增 1,然後重新分配其值。
示例程式碼
#include <stdio.h>
int main(void) {
int n = 12;
printf("The initial value of number n is %d
", n);
n = n+ 1;
printf("The value after adding 1 to the number n is %d", n);
return 0;
}輸出
The initial value of number n is 12 The value after adding 1 to the number n is 13
方法 2 − 使用增量運算子
此方法使用增量運算子將 1 新增到給定數字。這是將 1 新增到數字的一種快捷技巧。
示例程式碼
#include <stdio.h>
int main(void) {
int n = 12;
printf("The initial value of number n is %d
", n);
n++;
printf("The value after adding 1 to the number n is %d", n);
return 0;
}輸出
The initial value of number n is 12 The value after adding 1 to the number n is 13
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP