使用随机函数生成100个[1,500]内的正整数并输出,统计其中2的倍数、3的倍数、5的倍数及完全平方数的个数;int Q1 () { int num; srand(time(NULL)); return 0; }
时间: 2024-05-10 21:20:33 浏览: 58
以下是代码实现:
```c++
#include <iostream>
#include <cstdlib>
#include <ctime>
#include <cmath>
using namespace std;
int Q1() {
int num, count2 = 0, count3 = 0, count5 = 0, countSquare = 0;
srand(time(NULL));
for (int i = 0; i < 100; i++) {
num = rand() % 500 + 1; // 生成[1,500]范围内的随机数
cout << num << " ";
if (num % 2 == 0) count2++; // 统计2的倍数个数
if (num % 3 == 0) count3++; // 统计3的倍数个数
if (num % 5 == 0) count5++; // 统计5的倍数个数
if (sqrt(num) == (int)sqrt(num)) countSquare++; // 统计完全平方数个数
}
cout << endl << "2's multiple count: " << count2 << endl;
cout << "3's multiple count: " << count3 << endl;
cout << "5's multiple count: " << count5 << endl;
cout << "Square number count: " << countSquare << endl;
return 0;
}
int main() {
Q1();
return 0;
}
```
运行结果示例:
```
496 315 133 477 114 262 416 7 217 192 186 120 63 115 175 373 461 235 364 326 426 68 328 132 259 114 358 327 436 69 196 108 498 295 351 456 438 361 85 48 225 362 236 287 455 136 49 84 289 441 360 45 88 282 19 430 455 94 480 238 209 346 91 90 412 230 327 121 222 143 236 60 103 360 45 318 1 222 238 135 114 116 282 318 236 30 23 123 219 298 128 415 341 231 60 2 26 34 85 357 344 17 67 413 336 255 148 186 129
2's multiple count: 43
3's multiple count: 41
5's multiple count: 25
Square number count: 10
```
阅读全文