將 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

更新於: 2020 年 6 月 30 日

1K+ 次瀏覽

開啟您 職業生涯

完成課程以獲得認證

開始
廣告
© . All rights reserved.