首页 > 文章列表 > 给定一个数,加1

给定一个数,加1

数加一
251 2023-08-26

A program to add 1 to a given number increments the value of the variable by 1 . This is general used in counters.

There are 2 methods to increase that can be used to increase a given number by 1 −

  • Simple adding of one to the number and reassigning it to the variable.

  • Using increment operator in the program.

Method 1 − using reassignment method

This method takes the variable, add 1 to it and then reassigns its value.

Example Code

 Live Demo

#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; }

Output

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; }

Output

The initial value of number n is 12
The value after adding 1 to the number n is 13