■ struct 키워드를 사용하고 BMI 판정표를 만들고 체질량 지수(Body Mass Index)를 판정하는 방법을 보여준다.
▶ 예제 코드 (RS)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 |
fn main() { let body : Body = Body::new(163.0, 75.2, "영희"); body.print_result(); let body: Body = Body::new(158.2, 55.0, "진희"); body.print_result(); let body: Body = Body::new(174.2, 54.2, "문희"); body.print_result(); } struct BMIRange { minimum : f64, maximum : f64, label : String } impl BMIRange { fn new(minmum : f64, maximum : f64, label : &str) -> Self { return BMIRange { minimum : minmum, maximum : maximum, label : label.to_string() }; } fn test(&self, value : f64) -> bool { return (self.minimum <= value) && (value < self.maximum); } } struct Body { height : f64, weight : f64, name : String } impl Body { fn new(height : f64, weight : f64, name : &str) -> Self { return Body { height : height, weight : weight, name : name.to_string() }; } fn calculate_bmi(&self) -> f64 { return self.weight / (self.height / 100.0).powf(2.0); } fn print_result(&self) { let bmi : f64 = self.calculate_bmi(); let bmi_range_array : [BMIRange; 6] = [ BMIRange::new( 0.0, 18.5, "저체중" ), BMIRange::new(18.5, 23.0, "정상" ), BMIRange::new(23.0, 25.0, "비만전단계"), BMIRange::new(25.0, 30.0, "1단계 비만"), BMIRange::new(30.0, 35.0, "2단계 비만"), BMIRange::new(35.0, 99.9, "3단계 비만") ]; let mut result : String = String::from("계산 불가"); for range in bmi_range_array { if range.test(bmi) { result = range.label.clone(); break; } } println!("성명 : {}, BMI : {:.1}, 결과 : {}", self.name, bmi, result); } } |