วันพฤหัสบดีที่ 6 มกราคม พ.ศ. 2554

การรับค่าข้อมูล

การรับค่าข้อมูล
ในการรับค่าข้อมูลในภาษาซี จะมีคำสั่งมาตรฐานในการรับค่าข้อมูล ผ่านทางอุปกรณ์อินพุทมาตรฐาน(ซึ่งในที่นี้คือ แป้นพิมพ์) คำสั่งนั้นคือ scanf  (อ่านว่า สะ-แกน-เอฟ)
ตัวอย่างเช่น เมื่อผู้เขียนโปรแกรม ต้องการเขียนโปรแกรมให้คำนวณปริมาตรของกล่องสี่เหลี่ยมใดๆ ซึ่งมีสูตรในการคำนวณคือ กว้าง*ยาว*สูง ผู้เขียนโปรแกรมจะต้องรับค่าความกว้าง, ความยาวและความสูงของกล่องมาคำนวณ ดังนี้

#include <stdio.h>
int main()
{    int height,width,length;
printf(”Please enter height of box\n”);
scanf(“%d”, &height);
printf(”Please enter width of box\n”);
scanf(“%d”, &width);
printf(”Please enter length of box\n”);
scanf(“%d”, &length);
printf(”\n”);
printf(”The volume of this box is %d\n”, height*width*length);
     return 0;
}

ผลลัพธ์

Please enter height of box
12
Please enter width of box
12
Please enter length of box
10

The volume of this box is 1440
 
 


จากตัวอย่างดังกล่าว ได้มีการกำหนดตัวแปร height,width,length  เป็นแบบจำนวนเต็ม เพื่อรับค่าความสูง, ความกว้าง และความยาว ตามลำดับ มาใช้การคำนวณ และข้อสังเกตคือจะมีการใส่เครื่องหมายหน้าตัวแปรเพื่อใช้ในการรับค่า นอกจากนี้ผู้เขียนโปรแกรมสามารถรับค่าของความสูง, ความกว้าง และความยาว ภายในครั้งเดียวได้ แทนที่จะรับค่าทีละบรรทัด ดังตัวอย่าง

#include <stdio.h>
int main()
{    int height,width,length;
printf(”Please enter height, width and length of box\n”);
scanf(“%d %d %d”, &height, &width, &length);
printf(“\n”);
printf(”The volume of this box is %d\n”, height*width*length);
     return 0;
}

ผลลัพธ์

Please enter height, width and length of box
12 12 10

The volume of this box is 1440
 







ตัวอย่างของการใช้ scanf กับข้อความซึ่งใช้ %s และเป็นกรณียกเว้นที่ไม่ต้องใส่ & หน้าชื่อตัวแปร

#include <stdio.h>
int main()
{    char name[15];
printf(”Please enter your name\n”);
scanf(“%s”, name);
printf(”Your name is %s\n”, name);
     return 0;
}

ผลลัพธ์

Please enter your name
Thana
Your name is Thana
 
 

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

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