วันพฤหัสบดีที่ 18 กรกฎาคม พ.ศ. 2556

=Array=(hard)

Programming Exercise
Proposition =>  Write a program that reads eleven numbers, computers their average, and finds out how                                many number are below the average.
Translated into Thailand => ให้เขียนโปรแกรมที่คำนวณค่าเฉลี่ยของเลขทั้ง 11 ตัว และ หาว่ามีกี่ตัวที่มีค่าน้อยกว่าค่าเฉลี่ย

Solution=>

int[] n= {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11};
int i=1;
int av=0;
int sum=0;
int c=0;
int x=n[0];
while (i<n.length) {

  sum=x+n[i];
  x=sum;
  av=sum/11;
  i=i+1;
}


if (i>=n.length) {
  i=0;
  while (i<n.length) {
    if (n[i]<av) {
      c=c+1;
    }
    i=i+1;
  }
}
println("How many number are below the average?");
println("average="+av+" answer="+c);

Out put => How many number are below the average?
                       average=6 answer=5

You can run code in http://processingjs.org/tools/processing-helper.html


อธิบายการทำงานของโปรแกรม =>
ใส่ตัวเลขที่ต้องการคำนวณทั้งหมด11ตัวใน
 int[] n= {x1, x2, x3, x4, x5, x6, x7, x8, x9, x10, x11};
ในที่นี้กำหนดให้เป็น  int[] n= {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11}; กำหนดให้ค่า i=1, x=n[0]
เช็คเงื่อนไขของwhile ว่า i<n.length
 (n.length คือ จำนวนตัวแปลทั้งหมดที่มีใน n ในที่นี้คือ11 )
เมื่อเป็นจริง เริ่มทำการวนลูป ทำตามคำสั่งด้านในจนกว่าเงื่อนไขจะเป็นเท็จ จะจบการวนลูป
และเริ่มพิจารณาที่เงื่อนไขของif ต่อ ว่า i>=n.length(ซึ้งเมื่อจบจากการวนลูปแล้ว i=11)
เมื่อเป็นจริง ทำตามคำสั่งใน if ทำให้ค่า i=0 และพิจารณาเงื่อนไขของ while ที่อยู่ข้างใน if
ว่า i<n.length เมื่อเป็นจริง จำเริ่มทำการวนลูป โดยภายในลูปมี เงื่อนไข if ว่า n[i]<av (average)
เมื่อเป็นจริงให้ทำการเพิ่มค่าc 1หน่วย ทำการวนลูปไปเรื่อยๆ จนกว่าเงื่อนไขจะเป็นเท็จ
จะได้ค่า c=จำนวนตัวเลขที่มีค่าน้อยกว่าค่าเฉลี่ย

text book name : Introdution to Programming with C++
Author : Y.Daniel  Liang




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

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