วันจันทร์ที่ 5 สิงหาคม พ.ศ. 2556

Variable (Hard)

[Hard]

3. Write an application to calculate the diameter, circumference, and area of a circle with a radius input by the user. Assign the radius to a float variable, and then output the radius with an appropriate message. Declare a named constant PI with the value 3.14159. The application should output the diameter, circumference, and area, each on a separate line, with identifying labels. Be sure to include appropriate comments in your code, choose meaningful identifiers, and use indentation as we do in the code in this chapter.

(จงเขียนวิธีการคำนวณเส้นผ่านศูนย์กลาง เส้นรอบวง และพื้นที่ของวงกลมด้วยรัศมีที่เป็นตัวนำเข้าโดยผู้ใช้ สมมติค่าคงที่ PI ด้วยค่า 3.14159 วิธีการใช้ควรแสดงค่าของเส้นผ่านศูนย์กลาง เส้นรอบวง และพื้นที่ โดยแต่ละค่าบนแต่ละบรรทัด ด้วยสัญลักษณ์ที่มีการระบุ จงทำให้แน่ใจที่จะรวมความคิดเห็นที่เหมาะสมในโค้ดของคุณ เลือกตัวระบุค่าที่ให้ความหมายดี และใช้การอธิบายในแต่ะละบรรทัด ขณะที่พวกเราทำในโค้ดในบทนี้)

Code

float Radius = 80.5;
float PI = 3.14159;
float Diameter;
float Circumference;
float Area;
Diameter = 2*Radius;
Circumference = 2*PI*Radius;
Area = PI*Radius*Radius;
println("Diameter = "+Diameter);
println("Circumference = "+Circumference);
println("Area = "+Area);

Result

Diameter = 161.0
Circumference = 505.79602
Area = 20,358.29

อันดับแรกเราต้องกำหนดที่ให้ความหมายได้อย่างชัดเจน และมีค่าเป็นทศนิยมด้วยฟังก์ชั่น float ในที่นี้ ผมกำหนดให้ทุกตัวมีค่าเป็นทศนิยม หลังจากนั้นจึงสร้างสูตร ซึ่งเราดัดแปลงมาจากสูตรของวงกลมที่ใช้ในการเรียนตามปกติให้อยู่ในรูปแบบของโค้ด ต่อมา เราจึงสร้างคำสั่งที่จะทำให้ผลลัพธ์นั้นถูกแสดงออกมาด้วยฟังก์ชั่น println พร้อมทั้งระบุค่าที่เราต้องการให้แสดงไว้ข้างใน

ชื่อหนังสือ : PROGRAMMING AND PROBLEM SOLVING WITH JAVA SECOND EDITION
คนแต่ง : Nell Dale & Chip Weems หรือ 978-0-7637-3402-2
ISBN : 0-7637-3402-0
Page : 212 ข้อ 4


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

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