如何找到C++中一个范围内有多少个数字



我编写了一个程序来生成一组10000个随机数,平均值为1000,标准偏差为100。程序的这一部分有效。我正在努力解决的是,在这10000个数字中,我必须找到其中有多少在500到1500之间。正如你在我的代码中看到的那样,我尝试了while循环,但失败了。它返回介于500和1500之间的0个数字。

#include <random>
#include <cstdlib>
#include <ctime>
#include <iostream>
#include <conio.h>
#include <stdio.h>
#include<vector>  
using namespace std;
int main() {
int n = 10000;
int mean = 1000; 
float stdev = 100;
int maxNum = 1500;
int minNum = 500;
int count = 0;
int number;
int min = std::min(maxNum, minNum);
int max = std::max(maxNum, minNum);
default_random_engine randEng; 
randEng.seed(10);
normal_distribution<>normal(mean,stdev); 

for (int i = 0; i < n; i++) {
number = normal(randEng);
count++;
}
if (number >= min && number <= max) {
count++;
}
if(count = 1) {
std::cout << "There is " << count << " number between 500 and 1500 in the distriubtion" << std::endl;
} else if (count > 1) {
std::cout << "There are  " << count << " numbers between 500 and 1500 in the distriubtion" << std::endl;
} else {
std:cout << "There are no numbers between 500 and 1500" << std::endl;
}
getch();
return 0;
}

您的结构是错误的,并且您未能正确使用normal_distribution(实际上(。

#include <random>
#include <iostream>
#include <algorithm>
int main() {
int n = 10000;
int mean = 1000;
float stdev = 100;
int maxNum = 1100;
int minNum = 900;
int count = 0;
int number;
int min = std::min(maxNum, minNum);
int max = std::max(maxNum, minNum);
std::default_random_engine randEng;
randEng.seed(10);
std::normal_distribution<>normal(mean, stdev);

for (int i = 0; i < n; i++) {
number = static_cast<int>(normal(randEng));
if (number >= min && number <= max)
++count;
}
std::cout << "There are " << count << " numbers between " << min << " and " << max << " in the distributionn";
std::cin.get();
return 0;
}

输出

There are 6867 numbers between 900 and 1100 in the distribution

分布范围越广,所包含的数字就越多。注意分发对象与生成器的协同使用:

number = static_cast<int>(normal(randEng));

同样需要注意的是,count的累积在生成器循环内部,而不是三次更新的代码在循环外部,因此只执行一次。

最新更新