3x2二维数组列求和结果不符,及数组生成20-50随机数求助
解决3x2数组列求和错误与随机数生成问题
首先咱们先搞定列求和的bug——这类问题大多是循环索引搞混或者数组越界导致的,我拿两种常用语言举例分析:
一、列求和的错误修复
常见错误场景(以C++为例)
很多新手会不小心把列和的索引写成行索引,直接导致数组越界或计算结果完全错误:
int arr[3][2] = {{1,2},{3,4},{5,6}}; int column_sums[2] = {0}; // 错误:用行索引i访问列和数组,当i=2时会触发越界 for(int i=0; i<3; i++){ for(int j=0; j<2; j++){ column_sums[i] += arr[i][j]; } }
正确实现(C++)
核心逻辑是:先遍历每一列,再累加该列下所有行的元素:
int arr[3][2] = {{1,2},{3,4},{5,6}}; int column_sums[2] = {0}; // 先遍历列索引j for(int j=0; j<2; j++){ // 再遍历每一行i,累加当前列的元素 for(int i=0; i<3; i++){ column_sums[j] += arr[i][j]; } } // 输出结果:9 12 for(int sum : column_sums){ cout << sum << " "; }
正确实现(Python)
Python里写法更简洁,核心逻辑和C++一致:
# 示例3x2数组 arr = [[1, 2], [3, 4], [5, 6]] column_count = len(arr[0]) # 确定列数为2 column_sums = [0] * column_count # 遍历每一列 for j in range(column_count): # 累加该列的所有行元素 for row in arr: column_sums[j] += row[j] print("每列的和:", column_sums) # 输出:[9, 12]
二、生成20-50之间的随机数数组
Python实现
用random模块的randint()直接生成闭区间[20,50]的整数,再用列表推导式快速生成3x2数组:
import random # 生成单个20-50的随机数 single_random = random.randint(20, 50) # 生成3x2的随机数组 random_arr = [[random.randint(20, 50) for _ in range(2)] for _ in range(3)] print("随机数组:") for row in random_arr: print(row)
C++实现
用rand()配合取模运算,记得先初始化随机种子避免每次生成相同的序列:
#include <iostream> #include <cstdlib> #include <ctime> using namespace std; int main(){ srand(time(0)); // 用当前时间初始化随机种子 int random_arr[3][2]; for(int i=0; i<3; i++){ for(int j=0; j<2; j++){ // rand()%31 得到0-30,加20后就是20-50的整数 random_arr[i][j] = rand() % 31 + 20; } } // 打印随机数组 cout << "随机数组:" << endl; for(int i=0; i<3; i++){ for(int j=0; j<2; j++){ cout << random_arr[i][j] << " "; } cout << endl; } return 0; }
内容的提问来源于stack exchange,提问作者Michael Kofi Afriyie
相关产品推荐
相关产品推荐

