C++ 学习笔记7

 

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

 

 

你可能感兴趣的:(C++ 学习笔记7)