Use a map to create a table of foods and calories per portion. For example carrots-45, ice cream-250, and so on. Place at least 10 foods in your map. Use a random number generator to pick 4 foods per meal. Print out the meal and its calorie total.
使用map建立一個包含食物和其對應卡路裡的表,例如,胡蘿蔔-45,冰淇淋-250,等等。map中至少包含10種食物,每餐隨機挑選4種食物,列印所選食物及其卡路裡。
//本程式用VCSP6編譯通過
#include <iostream>
#include <string>
#include <stdlib.h>
using namespace std;
#include <map>
typedef std::map<string,int>Food;
int main()
{
Food food;
int a[5]={0};
int i=0;
cout<<"there are several kinds of food\n";
cout<<"1:mutton"<<endl;
cout<<"2:tomato"<<endl;
cout<<"3:potato"<<endl;
cout<<"4:carrot"<<endl;
cout<<"5:pumpkin"<<endl;
cout<<"6:pork"<<endl;
cout<<"7:beef"<<endl;
cout<<"8:onion"<<endl;
cout<<"9:spinach"<<endl;
cout<<"10:radish"<<endl;
cout<<"11:laver"<<endl;
//put all the food
//插入對應食物和卡洛裡
food.insert(Food::value_type("mutton",300));
food.insert(Food::value_type("tomato",50));
food.insert(Food::value_type("potato",45));
food.insert(Food::value_type("carrot",45));
food.insert(Food::value_type("pumpkin",50));
food.insert(Food::value_type("pork",300));
food.insert(Food::value_type("beef",400));
food.insert(Food::value_type("onion",100));
food.insert(Food::value_type("spinach",100));
food.insert(Food::value_type("radish",50));
food.insert(Food::value_type("laver",70));
cout<<"your food calories:\nfood\t\t\tcalories\n";
while(i<4)
{
int flag=1+rand() % 10; // 使用隨機函數
int j=0;
for(Food::const_iterator iter = food.begin(); iter != food.end(); ++iter,++j)
{
if(flag==j&&a[j] != 1)
{
cout<<iter->first<<"\t\t\t"<<iter->second<<endl;
i++;
a[j]=1;
break;
}
}
}
return 0;
}