算法入门(二分法—猜价格游戏)

问题:首先出示一件价格在999元以内商品,参与者要猜出这件商品的价格,在猜价格的过程中,主持人会根据参与者猜的价格进行相应的提示,“高了”或“底了”

代码实现:

#include<iostream>
#include<stdio.h>
#include<stdlib.h>
#include<cstring> 
#include<conio.h>
using namespace std;
int main(){
    int old_price,price = 0;
    int i = 0;
    cout<<"请输入商品的初始价格:";
    cin>>old_price;
    system("cls");
    cout<<"请输入试猜的价格:"<<endl;
    while(old_price != price){
        i++;
        cout<<"参与者:";
        cin>>price;
        cout<<"主持人:";
        if(old_price>price){
            cout<<"底了!"<<endl; 
        }
        else if(old_price<price){
            cout<<"高了!"<<endl;
        }
        else{
            cout<<"恭喜你猜对了,商品是你的了!\n\n你一共猜了:"<<i<<""<<endl;
        }    
    }
    getch();
    return 0;     
} 

posted @ 2018-11-02 21:29  无心小男  阅读(1831)  评论(0编辑  收藏  举报