【算法】美团之大富翁问题(C++源码)

一、问题描述

玩家根据骰子的点数决定走的步数,即骰子点数为1时可以走一步,点数为2时可以走两步,点数为n时可以走n步。求玩家走到第n步(n小于等于骰子最大点数且投骰子方法唯一)时总共有多少种投骰子的方法。

二、输入描述

输入一个1至6之间的整数

三、输出描述

输出一个整数,表示投骰子的方法数例如,输入为6时,输出为32.

四、步骤描述

a[1]=1;
a[2]=a[1]+1=2;
a[3]=a[2]+a[1]+1=4;
a[4]=a[3]+a[2]+a[1]+1=7;
……
a[6]= a[5]+a[4]+a[3]+a[2]+a[1]+1=32;

五、运行结果截图

1
2
3
4
5
6
6
7

六、源代码(C++)

#include <iostream>

using namespace std;

int main()
{
    int a[7];
    for(int i=1;i<=6;i++)
    {
        a[i]=1;
    }
    for(int i=1;i<=6;i++)
    {
        for(int j=1;j<=i-1;j++)
        {
            a[i]=a[i]+a[j];
        }
    }
    int x;
    cout<<"Please enter the steps the player needs to take : ";
    cin>>x;
    if(x>6 || x<=0)
    {
        cout<<"Please enter a number of steps less than six and greater than zero ! "<<endl;
    }
    else
    {
        cout<<"There are "<<a[x]<<" ways to throw dice"<<endl;
    }
    return 0;
}

版权声明:本文为Gyangxixi原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。