如何返回随机参数?

时间:2016-04-20 04:50:46

标签: c++ templates random

Template<typename T>
T Choose(T x, T y, T z)
{
  //What code do i write so that when Choose() is called it would randomly 
  // return x y or z?

   return;
}

例如,如果x = 2,y = 10且z = 4那么它将不会选择2,10或4来返回

2 个答案:

答案 0 :(得分:1)

将所有参数放在列表中。从列表开头到列表末尾选择一个随机数并返回该参数。注意,我不熟悉写lines = ["195,191", "22,23", "18,252", "172,221"] for i in lines: print "goto("+ i.split(',')[0] +"position,("+i.split(',')[1] +" * xy) - y) " 所以请在这里原谅goto(195+position,(191 * xy) - y) goto(22+position,(23 * xy) - y) goto(18+position,(252 * xy) - y) goto(172+position,(221 * xy) - y) 代码。这应该足以让您了解如何完成此任务。

C++

答案 1 :(得分:1)

#include <stdlib.h>

Template<typename T>
T Choose(T x, T y, T z)
{
    std::array<T*,3> temp{&x,&y,&z}; // or use std::reference_wrapper instead
    auto rand_index=std::rand() % temp.size();
    return *temp[rand_index];
}
相关问题