用C++编写一个24点游戏

这是一个使用C++编写的24点游戏程序,它实现了中缀表达式转后缀表达式,并通过栈来计算后缀表达式的值。用户可以输入包含随机数字和运算符的表达式,程序会检查是否能得到24点。
摘要由CSDN通过智能技术生成
#include<stdio.h>
#include<string>
#include<iostream>
#include<time.h>
#include<stdlib.h>
#include<conio.h>
using namespace std ;
typedef char type ;
//定义栈的结构体 
typedef struct  s
{
	type stk[10] ; 
	int top ; 
} Stack ;

///初始化 
int Initial( Stack &num  )
{
	num.top = -1 ;
	return 1 ;
}
///入栈
int push(Stack &num , char number )
{
    num.top++ ; 
	if( num.top < 10 )
	{
		num.stk[num.top] = number ;
	}
	else
	{
		printf("栈已满不能输入\n");
		return 0 ;
	}
	return 1 ;
}
///出栈
int pop( Stack &num , string &number )
{
    if( num.top >= 0 )
	{
		number += num.stk[num.top] ; 
	}
	else
	{
		printf("栈已空不能出战 \n");
		return 0 ;
	}
	num.top--;
	return 1 ; 
}

int pop1( Stack &num , char &number )
{
    if( num.top >= 0 )
	{
		number = num.stk[num.top] ; 
	}
	else
	{
		printf("栈已空不能出战 \n");
		return 0 ;
	}
	num.top--;
	return 1 ; 
}
/// 运算符优先级比较
int cmp(char a)
{
	switch(a)
	{
	case '+':
	case '-':  return 1 ;
	case '*':
	case '/':  return 2 ;
    default :  return 0 ;
	}
}
//中缀表达式转后缀表达式 
string hou_express(string str)
{
	int i ; 
	int flag = 0 ; 
	Stack num ; 
	string str1="",str2="" ;
	Initial(num);
	//cin>>str ; 
	for( i = 0 ; str[i] !='\0' ; i++ )
	{
		if(str[i] == '_')
		{
			str[i]=' ';
			str1+=str[i] ;
			continue ;
		}
		if( str[i] == '(' )
		{
            flag = 1 ;
            push(num , str[i]) ;
			continue ;
		}
		if(str[i] == ')')
		{
			while(num.stk[num.top] != '(' )
			pop(num 
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值