2023.2.26上机练习

1.两个人A和B猜数,A B商定一个数字 n,A从1到n之间选一个数 x,B来猜这个数,A会告诉B是大了还是小了。B至少要多少次,才能确定A选的那个数?

输入格式
两个整数,分别是 n,x。

输出格式
一个整数,B至少猜的次数。

输入样例
100 10
输出样例
6
数据范围
n:[1, 1000], x:[1, n]。

/*
这个程序不知道为什么边界值猜数的时候结果错误哎...
#include<iostream>
using namespace std;
int main()
{
	int n, x;
	cin >> n >> x;
	int low=1,high=n,count=0,mid;
	while (low<high)
	{
		mid = (low+high) / 2;
		if (mid > x)
			low = mid+1;
		else if (mid < x)
			high = mid-1;
		else if(mid==x)
			break;
		count++;
	}
	cout << count << endl;
	return 0;
}*/


#include <algorithm>
#include <iostream>
#include <cstring>
#include <cmath>
using namespace std;

int main()
{
	int n, x, cnt = 0;
	cin >> n >> x;
	int l = 1, r = n;
	while (l < r)
	{
		int mid = l + r + 1 >> 1;
		if (mid <= x)   
			l = mid;
		else    
			r = mid - 1;
		cnt++;
	}
	cout << cnt;
	return 0;
}

2.输入n作为待排序的数字个数,然后利用排序方法输出从小到大的顺序。

输入格式
第一行:一个整数n,代表数组中数字的个数。 第二行:n个整数,代表数组中的n个数。

输出格式:
从小到大排好序的n个整数。

输入样例:
3
2 3 1
输出样例
1 2 3
数据范围
n: [1, 10000]

a[n]: [-10000, 10000]

#include<iostream>
#include<algorithm>
using namespace std;
int main()
{
	int n,arr[1000];
	cin >> n;
	for (int i = 0; i < n; i++)
		cin >> arr[i];
	sort(arr, arr + n);
	for (int i = 0; i < n; i++)
		cout << arr[i] << ' ';
	return 0;
}

3.问题描述
从键盘输入一个字符串,将该字符串按下述要求处理后输出:
将ASCII码大于原首字符的各字符按原来相互间的顺序关系集中在原首字符的左边,
将ASCII码小于等于原首字符的各字符按升序集中在原首字符的右边。

输入说明
输入一行字符串,字符串c不长度超过100.

输出说明
输出处理后的一行字符串

输入样例
aQWERsdfg7654!@#$hjklTUIO3210X98aY

输出样例
sdfghjkla!#$0123456789@EIOQRTUWXYa

#include<iostream>
#include<string.h>
using namespace std;
int main()
{
	char c[100], left[100], right[100], string[100];
	int i, j, k, l;
	char t;
	void sort(char* str, int n);

	//gets_s(str,参数)  参数:参数为存储字符串的空间长度
	//函数功能:在标准输入设备输入一个字符串,以"回车键"结束,并把字符串存放到 str 指定的字符数组或存储区域中。
	
	gets_s(c, 100);  //输入一行字符串并存入数组c中
	t = c[0];
	for (i = 1, j = 0, k = 0; i < strlen(c); i++)
	{

	//和首个字符比较大小
		if (c[i] > t)
			left[j++] = c[i];  //大于进入left数组
		else
			right[k++] = c[i];  //小于进入right数组
	}

	sort(right, k);  //小于数组排序

	//将left,c[0],right数组整合进入string数组
	for (i = 0, l = 0; i < j; i++)
		string[l++] = left[i];
	string[l++] = t;
	for (i = 0; i < k; i++)
		string[l++] = right[i];
	string[l] = '\0';
	
	//puts()函数用来向标准输出设备(屏幕)输出字符串并换行,具体为:把字符串输出到标准输出设备,将'\0'转换为回车换行。
	//puts输出字符串时要遇到'\0’也就是字符结束符才停止

	puts(string);
	return 0;
}
void sort(char* str, int n)
{
	int i, j;
	char t;
	for (i = 1; i < n; i++)
	{
		for (j = 0; j < n - i; j++)
		{
			if (str[j] > str[j + 1])
			{
				//交换函数
				t = str[j];
				str[j] = str[j + 1];
				str[j + 1] = t;
			}
		}
	}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值