用随机函数求5-10之间的数

 

此语句求的是5-10之间的整数:

 

x = (int)(Math.random()*5) + 5

random方法返回的是0-1之间的float的小数。

求解思路:

先用5乘 0-1之间的小数,结果的范围是: 0-5的小数,因为0*5=0,1*5=5.

然后转换成整数,最后加就5就变成(0到5)+5 也就是5到10的随机数了。

转载于:https://www.cnblogs.com/bingxing/p/8884365.html

以下是用C++编写的程序,调用函数随机生成0-99之间,放入5X4的矩阵,出每行元素之和的代码: ```c++ #include <iostream> #include <cstdlib> #include <ctime> using namespace std; void generateMatrix(int matrix[][4], int rows, int cols); // 随机生成矩阵 void printMatrix(int matrix[][4], int rows, int cols); // 打印矩阵 void sumRows(int matrix[][4], int rows, int cols); // 每行元素之和 int main() { const int rows = 5; // 矩阵的行 const int cols = 4; // 矩阵的列 int matrix[rows][cols]; // 定义矩阵 // 随机生成矩阵 generateMatrix(matrix, rows, cols); // 打印矩阵 cout << "矩阵为:" << endl; printMatrix(matrix, rows, cols); // 每行元素之和 sumRows(matrix, rows, cols); return 0; } void generateMatrix(int matrix[][4], int rows, int cols) { srand(time(NULL)); // 初始化随机种子 for (int i = 0; i < rows; i++) { for (int j = 0; j < cols; j++) { matrix[i][j] = rand() % 100; // 生成0-99之间随机 } } } void printMatrix(int matrix[][4], int rows, int cols) { for (int i = 0; i < rows; i++) { for (int j = 0; j < cols; j++) { cout << matrix[i][j] << "\t"; } cout << endl; } } void sumRows(int matrix[][4], int rows, int cols) { for (int i = 0; i < rows; i++) { int sum = 0; // 初始化每行元素之和为0 for (int j = 0; j < cols; j++) { sum += matrix[i][j]; // 每行元素之和 } cout << "第" << i + 1 << "行元素之和为:" << sum << endl; } } ``` 程序的运行结果: ``` 矩阵为: 29 4 58 10 33 5 62 65 51 22 56 16 98 41 45 23 63 36 93 10 第1行元素之和为:101 第2行元素之和为:165 第3行元素之和为:145 第4行元素之和为:207 第5行元素之和为:202 ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值