面试题几道--C/C++

来源:互联网 发布:手机视频录像软件 编辑:程序博客网 时间:2024/05/29 10:07
1.

21

22

23

24

25..

20

7

8

9

10

19

6

1

2

11

18

5

4

3

12

17

16

15

14

13

看清楚以上数字排列,设1的坐标是(0,0),x方向向右为正,y方向向下为正。例如7的坐标(-1,-1),2的坐标(0,1),3的坐标(1,1)。编程实现任意输入一点的坐标(x,y),输出其所对应的数字。

利用数学推导,(-t,t)的值为(2t+1)^2。由他开始,逆时针方向转圈,依次减一,一直减到(-t+1,t)。围成了一个正方形,可以求出四个直角处对应的值,然后对应输入的坐标,看他落到哪一条边上,利用对应直角的值可以方便的推导出来。

       这种方法不好,不是程序员的设计思想,程序的价值在于将复杂的推理运算交给计算机,感觉此方法本末倒置了。欢迎改良!!

 

//求出回旋数字,线下数学推导,方法较笨//设计时,没有考虑值溢出//version1.0 ,2012,11,2//created by fish#include<iostream>#include<math.h>using namespace std;long int value(int x, int y){    int t=(abs(x)>abs(y))?abs(x):abs(y);    int p=(2*t-1)*(2*t-1)+1;    if(x>=1-t&&y==t&&x<t)        return p+x+t-1;    if(x==t&&y>-t&&y<=t)        return p+2*t-1+abs(y-t);    if(y==-t&&x<=t&&x>-t)        return p+4*t-1+abs(x-t);    if(x==-t&&y>=-t&&y<=t)        return p+6*t-1+abs(-t-y);}int main(){    cout<<"please intput the location"<<endl;    int x,y;    cin>>x>>y;    cout<<"the value is:"<<endl<<value(x,y)<<endl;    return 0;}

2.  不使用if ,?:,switch ,while,对于输入的变量a,b,输出较大者的值。

       Ans:max=(a+b+abs(a-b))/2;

3.   不让第三者插足,交换变量a,b的值

       Ans: 按位异或运算(a^b^a)=b

              A=a^b;

              B=a^b;

              A=a^b;

4. 一个运动员射击打靶,靶一共有10环,也可能脱靶,请问,连开10枪打中90环的方案有多少种?

//打靶问题//递归有穷遍历//2012,11,02#include<iostream>#include<stdexcept>using namespace std;const int CiShu=10;const int SUM=90;int bazi[CiShu]={0};double count=0;void SheJi(int score ,int cishu){    if(score<0||score>(cishu+1)*10){        return;    }    if(cishu==0){        bazi[cishu]=score;        count++;        return;    }    for(int i=0;i<=CiShu;i++){        bazi[cishu]=i;        SheJi(score-i,cishu-1);    }}int main(){    SheJi(SUM,CiShu-1);    cout<<"总次数::"<<count<<endl;    return 0;}