Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> การเขียนโปรแกรม C

บวก 1 เข้ากับตัวเลขที่กำหนด


โปรแกรมบวก 1 เข้ากับตัวเลข เพิ่มค่าตัวแปรขึ้น 1 ใช้ทั่วไปในตัวนับ (counters)

มี 2 วิธีเพิ่มค่าขึ้น 1

  • บวก 1 แล้วกำหนดค่ากลับให้ตัวแปร
  • ใช้ increment operator

วิธี 1 - วิธีการกำหนดค่าใหม่

รับตัวแปร บวก 1 แล้วกำหนดค่าใหม่

โค้ดตัวอย่าง

#include <stdio.h> int main(void) { int n = 12; printf("The initial value of number n is %d \n", 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 - ใช้ increment operator

ใช้ ++ บวก 1 แบบ shorthand

โค้ดตัวอย่าง

#include <stdio.h> int main(void) { int n = 12; printf("The initial value of number n is %d \n", 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