C++ 学习笔记7

使用Map创建食物卡路里表并随机选取餐食
本程序使用Map数据结构创建一个包含多种食物及其卡路里值的表,并通过随机数生成器为每餐选择四种食物,输出所选食物及其卡路里总量。
 

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;
 
 
}

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值