iT邦幫忙

2021 iThome 鐵人賽

DAY 30
0
自我挑戰組

腦力激盪C++系列 第 30

[Day-30] 最後一天的小練習

首先要慶祝一下~
終於撐到30天了
/images/emoticon/emoticon01.gif

今天要來練習的是利用switch
來做一個選擇的模式
模式有三種

  1. 顯示現在的日期以及時間
  2. 顯示每日總熱量消耗
  3. 退出程式

廢話不多說
直接開始今天的練習吧~
/images/emoticon/emoticon07.gif

程式碼:

#include<iostream>
#include <ctime>
#include <math.h>
using namespace std;

int BMR(int tall, int weight, int sex, int age){
	float x;
	x = (9.99 * weight )+ (6.25 * tall) -(4.92*23) + ((166 * age) -161);
	return x;
}

int main(){	
	int select;
	int tall, weight, sex, age;
	while(true){
		cout<<"選擇模式:\n→ 日期/時間(1)\n→ 每日總熱量消耗(2)\n→ 退出(3)\n";
		cin>>select;
		cout<<'\n';
	       
		time_t now = time(0);
	    char* dt = ctime(&now);
	
	 	switch(select){
		 	case 1:
		        cout << "現在的日期/時間是:" << dt << '\n';
		 	break;
		 	
		 	case 2:
                cout << "請輸入您的性別:男(1)女(0)\n";
                cin >> sex;
                cout << "請輸入您的年齡\n";
                cin >> age;
                cout << "請輸入您的身高(cm)\n";
                cin >> tall;
                cout << "請輸入您的體重(kg)\n";
                cin >> weight;
                cout << "  ▼每日總熱量消耗▼\n";
                cout << "不太運動:"
                     <<ceil(BMR(tall, weight , age, sex)*1.2)<< "卡路里\n";
                cout << "偶爾運動:"
                     <<ceil(BMR(tall, weight , age, sex)*1.375)<< "卡路里\n";
                cout << "經常運動:"
                     <<ceil(BMR(tall, weight , age, sex)*1.55)<< "卡路里\n";
                cout << "每天運動:"
                     <<ceil(BMR(tall, weight , age, sex)*1.72)<< "卡路里\n";
                cout << "強度運動:"
                     <<ceil(BMR(tall, weight , age, sex)*1.9)<< "卡路里\n";
                break;
		    
		    case 3:
		    return false;
		    break;
		    
		    default:
		    break;
		}
 	}
 	return 0;
}

執行結果:

選擇模式:
→ 日期/時間(1)
→ 一天所消耗的卡路里算(2)
→ 退出(3)
1

現在的日期/時間是:Thu Oct 07 02:32:06 2021

選擇模式:
→ 日期/時間(1)
→ 一天所消耗的卡路里算(2)
→ 退出(3)
2

請輸入您的性別:男(1)女(0)
1
請輸入您的年齡
38
請輸入您的身高(cm)
175
請輸入您的體重(kg)
75
  ▼每日總熱量消耗▼
不太運動:2081卡路里
偶爾運動:2385卡路里
經常運動:2688卡路里
每天運動:2983卡路里
強度運動:3295卡路里
選擇模式:
→ 日期/時間(1)
→ 每日總熱量消耗(2)
→ 退出(3)
3
--------------------------------
Process exited after 0.08787 seconds with return value 0
請按任意鍵繼續...

程式碼解釋:
這邊引用了之前所學的數學函式庫
還有關於日期時間的函式庫

#include <math.h>
#include <ctime>

宣告一個型態為int的變數select
用來儲存選擇的模式
用while迴圈來重複執行選擇模式
再利用switch來寫選擇模式的三種模式
◆第一種模式
直接引入ctime的函式來去做計算
最後就會直接顯示結果

◆第二種模式
需先算出BMR(基礎代謝率)才能再繼續運算每日總熱量消耗
公式為:(9.99 × 體重) + (6.25 × 身高) - (4.92 × 年齡) +((166 × 性別 (男 1、女 0) - 161))
算出BMR後就可以計算每日的總熱量消耗有多少了

  • seldom:BMR × 1.2
  • sometimes:BMR × 1.375
  • often:BMR × 1.55
  • usually:BMR × 1.72
  • always:BMR × 1.9
    最後顯示時再利用數學函式庫math
    來讓小數點無條件進位
    就完成啦~

◆第三種模式
使用break跳出while迴圈
來完成退出的效果

以上就是我今天的練習啦~
終於結束30天了
謝謝大家的觀看~
/images/emoticon/emoticon08.gif

-End-
參考資料:https://tools.heho.com.tw/bmr/


上一篇
[Day-29] 小練習-動態進度條
系列文
腦力激盪C++30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言