1.功能函数
bool isNumber(char ch)
bool isOperator(char ch)
int calculate(char ch, int a, int b)
2.get函数
char ch=cin.get();
char ch=file.get();
char ch;
cin.get(ch);
char ch;
file.get(ch);
cin.get();
注意:get()会吸收前面打的回车,所以用get()之前先用cin.get()吸收掉回车,否则会出错
3.字符型与整型的转换
char ch='1';
int a=(int)ch;//a=49;
int b=(int)ch-'0';//b=1;
int c=(int)(ch-'0');//c=1;
但第二种应该是不好的,整型与字符型运算
4.栈
#include<stack>
stack<int> s;//定义
s.push(x);//入栈
s.pop();//删除栈顶元素,不返回值
int a=s.top();//返回栈顶元素
int length=s.size();//栈中元素个数
s.empty();//栈空返回true
MyAnswer
#include<iostream>
#include<stack>
#include<string>
using namespace std;
bool isNumber(char ch)
{
if (ch >= '1'&&ch <= '9')
return 1;
else
return 0;
}
bool isOperator(char ch)
{
if (ch == '+' || ch == '-' || ch == 'x' || ch == '/')
return 1;
else
return 0;
}
int calculate(char ch, int a, int b)
{
int result = 0;
switch (ch)
{
case'+':
result = b + a;
break;
case'-':
result = b - a;
break;
case'x':
result = b * a;
break;
case'/':
result = b / a;
break;
}
return result;
}
int main()
{
int n;
cin >> n;
string *array = new string[n];
for (int i = 0; i < n; i++)
{
cin.get();
char ch, c;//ch存储输入,c存储操作符栈顶元素
int result, a, b;//result存储计算结果
stack<int>numStack;
stack<char>chStack;
cin.get(ch);
numStack.push((int)(ch - '0'));
for (int i = 1; i < 7; i++)
{
cin.get(ch);
if (isOperator(ch) == 1)
chStack.push(ch);
else if (isNumber(ch) == 1)
{
c = chStack.top();
if (c == '+' || c == '-')
numStack.push((int)(ch - '0'));
else if (c == 'x')
{
a = (int)(ch - '0');
b = numStack.top();
result = calculate('x', a, b);
chStack.pop();
numStack.pop();
numStack.push(result);
}
else if (c == '/')
{
a = (int)(ch - '0');
b = numStack.top();
result = calculate('/', a, b);
chStack.pop();
numStack.pop();
numStack.push(result);
}
}
}
int sum = 0;
while (!chStack.empty())
{
int x = numStack.top();
char y = chStack.top();
sum = calculate(y, x, sum);
numStack.pop();
chStack.pop();
}
sum += numStack.top();
if (sum == 24)
array[i] = "Yes";
else
array[i] = "No";
}
for (int i = 0; i < n; i++)
cout << array[i] << endl;
return 0;
}