算法入門(二分法—猜價格游戲)


問題:首先出示一件價格在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;     
} 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM