华为笔试题01

  • 题目描述:

编写一个函数,将输入的3个数字进行四则运算看是否可以得出二十一。

如 3,7,1. 输出结果为1(表示可以,因为3*7*1 = 21).

只用+-*/四则运算

三个数字的顺序固定,运算不用考虑优先级

  • 要求实现函数:

void IsGetTyO (const int *pIn, int& nOut);

【输入】 pIn:  输入的3个数字

【输出】 nOut:是否可以计算出21(1表示可以,0表示不可以)

【注意】只需要完成该函数功能算法,中间不需要有任何IO的输入输出

        3个数字的顺序不会变化

  • 示例

输入:3,7,1

输出: 1

 

#include "stdafx.h"
#include <iostream>
using namespace std;
 
int calculate(int a ,int b,char c)
{
    switch(c)
    {
    case('+'):
        {
            return a+b;
            break;
        }
    case('-'):
        {
            return a-b;
            break;
        }
    case('*'):
        {
            return a*b;
            break;
        }
    case('/'):
        {
            return a/b;
            break;
        } 
    }
}
void IsGetTy0(const int *pIn,int &nOut)
{
    int a=pIn[0];
    int b=pIn[1];
    int c=pIn[2];
    int m=0;
    int out=0;
    char action[]={'+','-','*','/'};
    for(int i=0;i<4;i++)
    {
        for(int j=0;j<4;j++)
        {
            m=calculate(a,b,action[j]);
            if(calculate(m,c,action[i])==21)
            {
                cout<<"ok"<<endl;
                out=1;
                return ;
            }
        } 
    } 
}
int _tmain(int argc, _TCHAR* argv[])
{
    int test[3]={3,8,1};
    int rel;
    IsGetTy0(test,rel);
    return 0;
}

  

  

 

 

原文地址:https://www.cnblogs.com/xd-jinjian/p/3275817.html