รูปที่ 2-3 แสดงการประกาศตัวแปรแบบต่าง ๆ
การกำหนดค่าให้กับตัวแปร
การกำหนดค่าให้กับตัวแปรนั้น จะสามารถกำหนดได้ตั้งแต่ตอนที่ประกาศตัวแปรเลยหรือจะกำหนดให้ภายในโปรแกรมก็ได้ ซึ่งการกำหนดค่าจะใช้เครื่องหมาย = กั้นตรงกลาง
int total = 0;
ถ้ามีตัวแปรข้อมูลชนิดเดียวกัน ก็สามารถทำแบบนี้ได้
int total =0,sum
หรือ
int total =0,sum=0;
ถ้าเป็นการกำหนดภายในโปรแกรม ซึ่งตัวแปรนั้นได้ประกาศไว้แล้วสามารถทำแบบนี้
total = 50;
หรือ
total = total+sum
หรือกำหนดค่าจาการพิมพ์ข้อมูลเข้าทางคีย์บอร์ด
scanf(“%d”,&total);
int total =0,sum
หรือ
int total =0,sum=0;
ถ้าเป็นการกำหนดภายในโปรแกรม ซึ่งตัวแปรนั้นได้ประกาศไว้แล้วสามารถทำแบบนี้
total = 50;
หรือ
total = total+sum
หรือกำหนดค่าจาการพิมพ์ข้อมูลเข้าทางคีย์บอร์ด
scanf(“%d”,&total);
โปรแกรมที่ 2-2 การประกาศและใช้ตัวแปร
#include<stdio.h>
/*การประกาศตัวแปร Global*/
int sum = 0;
int main(void)
{
/*การประกาศตัวแปรแบบ Local */
int a;
int b;
int c;
/*คำสั่ง */
printf(“\nWelcome. This Program adds\n”);
printf(“threenumbers.Enter three numbers\n”);
printf(“in the form: nnn nnn nnn <retur>\n”);
scanf(“%d %d %d”,&a,&b,&c);
/* ทำการบวกค่าระหว่าง a,b และ c เข้าด้วยกันแล้วกำหนดค่าให้ sum*/
sum=a+b+c;
printf(“The total is: %d\n”,sum);
printf(“Thant you. Have a good day.\n”);
return 0;
}
ผลการทำงาน:
Welcome. This Program adds
Three numbers. Enter three number
In the form: nnn nnn nnn <return>
11 22 23
The total is: 56
Thank you. Have a good day.
#include<stdio.h>
/*การประกาศตัวแปร Global*/
int sum = 0;
int main(void)
{
/*การประกาศตัวแปรแบบ Local */
int a;
int b;
int c;
/*คำสั่ง */
printf(“\nWelcome. This Program adds\n”);
printf(“threenumbers.Enter three numbers\n”);
printf(“in the form: nnn nnn nnn <retur>\n”);
scanf(“%d %d %d”,&a,&b,&c);
/* ทำการบวกค่าระหว่าง a,b และ c เข้าด้วยกันแล้วกำหนดค่าให้ sum*/
sum=a+b+c;
printf(“The total is: %d\n”,sum);
printf(“Thant you. Have a good day.\n”);
return 0;
}
ผลการทำงาน:
Welcome. This Program adds
Three numbers. Enter three number
In the form: nnn nnn nnn <return>
11 22 23
The total is: 56
Thank you. Have a good day.
ไม่มีความคิดเห็น:
แสดงความคิดเห็น