201903 CCF

201903-1 小中大

有点坑,注意除不尽要四舍五入保留一位小数,注意整数要除以2.0
#include <iostream>
#include <cmath>
#include <algorithm> 
#include <vector>
#include <iomanip>
using namespace std; 
int main(int argc, char** argv) {
	int n;
	cin>>n;
	int a[n];
	for(int i=0;i<n;i++){
		cin>>a[i];
	}
	if(a[0]>=a[n-1]){
		cout<<a[0]<<" ";
	}else{
		cout<<a[n-1]<<" "; 
	}
	if(n%2==0){
		if((a[n/2]+a[n/2-1])%2!=0){
			cout<<fixed<<setprecision(1)<<(a[n/2]+a[n/2-1])/2.0<<" ";
		}else{
			cout<<(a[n/2]+a[n/2-1])/2<<" ";
		}
	}else{
		cout<<a[n/2]<<" ";
	}
	if(a[0]>=a[n-1]){
		cout<<a[n-1];
	}else{
		cout<<a[0];
	}
	return 0;
}

201903-2 二十四点

主要考栈的操作还有栈实现中缀表达式
复习一下栈
#include<stack>  //头文件
stack<int> q;	//以int型为例
int n;
q.push(n);		//将n压入栈顶
q.top();		//返回栈顶的元素
q.pop();		//删除栈顶的元素
q.size();		//返回栈中元素的个数
q.empty();		//检查栈是否为空,若为空返回true,否则返回false
思路是B站曾经看过的Java课程

在这里插入图片描述

#include<iostream>
#include<stack>
#include<algorithm>
#include<string> 
using namespace std;
int getPriority(char s1);
int result(int num1,int num2,char oper);
int main()
{
	int n;
	cin>>n;
	string s;
	// 数字栈 
	stack<int> num;
	// 运算符栈
	stack<char> oper; 
	int temp,num1,num2,res,opers;
	
	for(int i=0;i<n;i++){
		cin>>s;
		// 扫描表达式 
		for(int j=0;j<s.length();j++){
			temp=s[j]-'0'; //转换成数字 
			// 数字直接进数字栈 
			if(temp>=0&&temp<=9){
				num.push(temp);
			}else{
				if(oper.empty()){ // 为空直接入栈 
					oper.push(s[j]);
				} else{ //判断优先级 
					if(getPriority(s[j])>getPriority(oper.top())){ //大于直接入栈 
						oper.push(s[j]); 
					}else{// 小于等于, 数字栈弹出两个数,符号栈弹出运算符进行运算 ,结果压入数栈,当前运算符压栈 
						num1=num.top();
						num.pop();
						num2=num.top();
						num.pop(); 
						opers=oper.top();
						oper.pop();
						res=result(num1,num2,opers);
						num.push(res);// 结果入栈
						oper.push(s[j]); // 当前运算符入栈 
					}
				}
			}
		}
		
		// 表达式遍历结束将数栈和运算符栈一次弹出计算结果,知道运算符栈为空 
		while(!oper.empty()) {
			num1=num.top();
			num.pop();
			num2=num.top();
			num.pop(); 
			opers=oper.top();
			oper.pop();
			res=result(num1,num2,opers);
			num.push(res);// 结果入栈
		}
		if(num.top()==24) cout<<"Yes"<<endl;
		else cout<<"No"<<endl; 
		num.pop();
	}
    return 0;
}
 
// 判断优先级 
int getPriority(char s1){
	if(s1=='x'||s1=='/'){
		return 1;
	}else if(s1=='+'||s1=='-'){
		return 0;
	}else{
		return -1;
	}
}

// 得到结果 
int result(int num1,int num2,char oper){
	int res;
	switch(oper){
		case '+':
			res=num1+num2;
			break;
		case '-':
			res=num2-num1; // 后减前
			break;
		case 'x':
			res=num1*num2;
			break;
		case '/':
			res=num2/num1;
			break;
		default:
			break;
	}
	return res;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值