วันจันทร์ที่ 5 พฤษภาคม พ.ศ. 2557

การแปลงตัวแปรชนิด float เป็น int

การแปลงตัวแปรชนิด float เป็น int

ตัวอย่างเช่น
float x,y;
int tableWidth;
int tableHeight;
void setup(){
    size(500,500);
    background(255, 255, 255, 255);
    frameRate(5);
    tableWidth = 200;
    tableHeight = 100;
  
}
void draw_table(int x,int y){
    line(x,y,x+tableWidth,y);
    line(x+10,y,x+10,y+tableHeight);
    line(tableWidth+x-10,y,tableWidth+x-10,y+tableHeight);
}
void draw(){
    background(255, 255, 255, 255);
    x=random(500);
    y=random(500);
    int newX = int(x);
    int newY = int(y);
    draw_table(newX,newY);  
}

จากตัวอย่าง ในเริ่มแรกจะประกาศค่า x,y เป็นชนิด float แต่เมื่อเราต้องการจะใช้ตัวแปร x,y ในชนิด int โดย

float x,y;
 int newX = int(x);
 int newY = int(y);


ตัวอย่างการ Error ของโปรแกรม
float x,y;
int tableWidth;
int tableHeight;
void setup(){
    size(500,500);
    background(255, 255, 255, 255);
    frameRate(5);
    tableWidth = 200;
    tableHeight = 100;
  
}
void draw_table(int x,int y){
    line(x,y,x+tableWidth,y);
    line(x+10,y,x+10,y+tableHeight);
    line(tableWidth+x-10,y,tableWidth+x-10,y+tableHeight);
}
void draw(){
    background(255, 255, 255, 255);
    x=random(500);
    y=random(500);
    draw_table(x,y);  
}

    จากตัวอย่าง เมื่อรันโปรแกรมแล้ว โปรแกรมจะขึ้นแจ้งว่า

    เนื่องจากฟังก์ชั่น draw_table(x,y); มีการส่งตัวแปรไปเป็น x และ y ซึ่งมีการกำหนดชนิดเป็น float ตั้งแต่แรก แต่ในฟังก์ชั่น void draw_table(int x, int y) นำค่า x และ y มากำหนดใช้เป็นชนิด int จึงไม่สามารถนำมาใช้ได้ โปรแกรมจึงแจ้ง Error


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

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