วันจันทร์ที่ 9 กันยายน พ.ศ. 2556

   ชนิดข้อมูลแบบค่าคงที่ (Constants)  



ชนิดข้อมูลประเภทนี้ ชื่อก็บอกอยู่ว่าเป็นชนิดข้อมูลแบบค่าคงที่ ซึ่งก็คือข้อมูลตัวแปรประเภทที่เป็น Constants ผู้ใช้จะไม่สามารถเปลี่ยนแปลงค่าของตัวแปรตัวนั้น ในขณะที่โปรแกรมทำงานอยู่ 



   รูปแบบ   

Const[ชนิดข้อมูล][ตัวแปร]=[ค่าหรือ นิพจน์]
ตัวอย่าง 
const folat a = 5.23;
const int b = a%2;

โปรแกรมที่ 2-4 การใช้ตัวแปรชนิดข้อแบบค่าคงที่
#include<stdio.h>
imt main(void)
{
const float pi = 3.14159;
float radius;
radius = 3;
printf(“Value of pi  : %f\n”,pi);
printf(“Value of area : %f\n”,pi*(radius*radius));
return 0;
}


ผลการทำงาน:
Value of pi : 3.141590
Value of area : 28.274311

constant นั้นสามารถแบ่งออกได้ ดังนี้
Integer Constants เป็นค่าคงที่ชนิดข้อมูลแบบตัวเลขจำนวนเต็มไม่มีจุดทศนิยม
const int a = 5;
Floating-Point Constants เป็นค่าคงที่ชนิดข้อมูลแบบตัวเลขที่มีจุดทศนิยม
const float b = 5.6394;
Character Constants เป็นค่าคงที่ชนิดตัวอักษร ซึ่งจะต้องอยู่ภายในเครื่องหมาย ‘’เท่านั้น
const char b = ‘t’;
String Constants เป็นค่าคงที่เป็นข้อความ ซึ่งจะต้องอยู่ภายใต้เครื่องหมาย “”เท่านั้น
“”
“h”
“Hello world\n”
“HOW ARE YOU”
“Good Morning!”

  โปรแกรมที่ 2-5 การใช้ตัวแปรชนิดข้อมูลแบบค่าคงที่แบบต่าง ๆ  
#includ<stdio.h>
int main(void)
{
const int a = 3; /*Integer Constats*/
const flat b = 3.14159; /*Floating – Point Constants*/
const cahr c = ‘P’; /*Character Constants*/
printf(“Value of a: %d\n”,a);
printf(“Value of b: %d\n”,b);
printf(“Value of c: %d\n”,c);
printf(“Good Bye”); /*String Constants*/
return 0;
}


  ผลการทำงาน   

Value of  a : 3
Value of  b : 3.141590
Value of  c : P
Good Bye


ไม่มีความคิดเห็น:

แสดงความคิดเห็น