目录
二分代码:
- #include <iostream>
- using namespace std;
- int n, num[1000005],x,q;
- int f(int x){
- int l = 0,r = n-1;
- int mid;
- while (l <= r){
- mid = (l+r)/2;
- if (num[mid] == x){
- return mid;
- }
- else if(num[mid] > x){
- r = mid-1;
- }
- else if(num[mid] < x){
- l = mid+1;
- }
- }
- return -1;
- }
- int main(){
- cin >> n;
- for (int i = 0; i < n; i++){
- cin >> num[i];
- }
- cin >> q;
- while (q--){
- cin >> x;
- cout << f(x) << "\n";
- }
- return 0;
- }
那是不是可以让c++做一个你想我猜的小游戏呢?
一个比较整蛊的小游戏
首先他会让你输入一个数
然后输出一大堆的字符,最后输出你那个数字
- #include <bits/stdc++.h>
- #include <unistd.h>
- using namespace std;
- int main(){
- cout << "我是读心术大师~\n";
- cout << "请你在键盘上随便乱摁几个数我能猜出他是什么~\n";
- string n;
- cin >> n;
- for (int i =0; i < 10; i++){
- cout << "—";
-
- sleep(1);
- }
- cout << "加载成功!";
- for (int i =0; i < 10000; i++){
- cout << "——";
- }
- cout << "\n你猜的数是:" << n;
- return 0;
- }
通过二分查找的方式乘一到1014去查找你心里想的那个数字.
- #include <iostream>
- #include <unistd.h>
- using namespace std;
- int main(){
- cout << "我们来猜数字吧!你想一个1~1024的数字,我会输出一个数字请你告诉我我是猜对了还是猜大了或者猜小了\n";
- int l = 0,r = 1024,m =0;
- int cnt = 0;
- while (l <= r){
- m = (l+r)/2;
- cout << m << "\n";
- cout << "我猜对了吗还是大了或者小了?\n对了:y 大了:b 小了:s";
- char a;
- cin >> a;
- if (a == 's' and m != 1024){
- l = m+1;
- }
- else if (a == 'b' and m != 1){
- r = m-1;
- }
- else if (a == 'y'){
- cout << "哈哈我猜对了";
- return 0;
- }
- else{
- printf("脑瘫~");
- break;
- }
- cnt += 1;
- if (cnt > 10){
- printf("你要想好一个数哦~\n");
- printf("别老是换来换去");
- break ;
- }
- }
- }