首页 文章

0到1之间的随机数Gen [C]

提问于
浏览
-2

所以我这位出色的CS老师已经决定让他的课程围绕着自己的安逸(而不是试图让他的学生更好地进行编程)....

但是,无论如何......他给我们提供了关于如何编写程序的一些信息,如果我们不像他那样写得完全正确,我们就不会得到信任 . 我想我已经写了一个工作程序(他做了他要求的),但是隐藏的测试用例一直在失败,所以我真的可以使用一些帮助 .

INSTRUCTIONS

  • 编写一个取整数“count”和双“概率”的函数

  • 生成介于0.0和1.0之间的“计数”随机数

  • 打印小于“概率”的生成随机数的数量

  • 从main()调用此新函数

CODE

#include <iostream>
#include <cstdlib>
using namespace std;

int newFunction(int count, double probability) {

   double random;
   int total;
   for(int i = 0; i < count; i++) {
      random = (double) rand() / RAND_MAX;
      if (random < probability) {
         cout << random << endl;
         total++;
      }
   }
   return total;
}

int main() {
  cout << "Enter integer for seed: " << endl;
  int seed;
  cin >> seed;
  srand(seed);

  int c;
  double p;
  cout << "Enter the count of numbers to be generated: " << endl;
  cin >> c;
  cout << "Enter the probability: " << endl;
  cin >> p;

  cout << "Number of generated random numbers less than probability entered is " << newFunction(c, p) << endl;

  return 0;
}

Program input is

1 //种子

3 //随机数的数量(计数)

0.5 //概率值

MY OUTPUT

输入种子的整数:

输入要生成的数字计数:

输入概率:

0.394383

生成的随机数小于输入的概率为1

HIS OUTPUT

输入种子的整数:

输入要生成的数字计数:

输入概率:

0.159812

0.216901

生成的随机数小于输入的概率为2

Default code given as template

#include <iostream>
#include <cstdlib>
using namespace std;

int newFunction(int count, double probability);

int main() {
  cout << "Enter integer for seed: " << endl;
  int seed;
  cin >> seed;
  srand(seed);

  int c;
  double p;
  cout << "Enter the count of numbers to be generated: ";
  cin >> c;
  cout << "Enter the probability: ";
  cin >> p;
  cout << "Number of generated random numbers less than probability entered is " << newFunction(c, p) << endl;

  return 0;
}

也许我写错了这个问题,但是这个问题与他给我们的不同之处在于编写代码的方式不同于以前的代码 . 我参加了许多CS课程,这是我第一次获得0分,这是一个功能正常/高效的程序 .

任何帮助都会很棒 . 多谢你们 .

1 回答

  • 0

    Fixed Code

    #include <iostream>
    #include <cstdlib>
    using namespace std;
    
    int newFunction(int count, double probability) {
    
       double random;
       int total = 0;
       for(int i = 1; i <= count; i++) {
          random = rand()/(double)(RAND_MAX + 1) + 1;
          if (random < probability) {
             cout << random << endl;
             total++;
          }
       }
       return total;
    }
    
    int main() {
      cout << "Enter integer for seed: " << endl;
      int seed;
      cin >> seed;
      srand(seed);
    
      int c;
      double p;
      cout << "Enter the count of numbers to be generated: " << endl;
      cin >> c;
      cout << "Enter the probability: " << endl;
      cin >> p;
    
      cout << "Number of generated random numbers less than probability entered is " << newFunction(c, p) << endl;
    
      return 0;
    }
    

    当我向RAND_MAX添加1时

    random = rand()/(double)(RAND_MAX + 1);
    

    我看到它给了我一个负面结果......所以我只是把它改成了

    random = rand()/(double)(RAND_MAX + 1) + 1;
    

    这解决了这个问题!

相关问题