[英]Loop fills array correctly then function returns array of all the same numbers?
[英]Array that fills using a loop *AND swaps
我在課堂上做了這個程序,並且試圖為即將來臨的考試重新創建它。 該程序應為array [2] [10],並應按以下順序輸出數字:
1 3 5 7 9 11 13 15 17 19
0 2 4 6 8 10 12 14 16 18
我真的迷失了,我真的可以使用任何幫助。
#include<iostream>
#include <string>
#include <cstring>
using namespace std;
void out(int n[2][10]);
void fillit(int n[2][10]);
int main(){
int nums[2][10];
fillit(nums);
out(nums);
}
void fillit(int n[2][10]){
n[0][0] = 1;
n[1][0] = 0;
for (int i = 1; i < 10; i++){
n[0][i] = n[0][i] + 2;
n[1][i] = n[0][i] + 2;
}
}
void out(int n[2][10]){
for (int r = 0; r <= 1; r++){
for (int c = 0; c <= 9; c++){
cout << n[r][c];
}
cout << endl;
}
}
更新我有程序成功填充數組,但是現在我需要程序將第1行與第2行交換,然后輸出新數組。 即0 2 4 6 8 10 12 14 16 18 1 3 5 7 9 11 13 15 17 19
void fillit(int n[2][10]){
for (int i = 0; i < 10; i++){
n[0][i] = (i * 2 ) + 1;
n[1][i] = i * 2;
}
}
#include<iostream>
#include <string>
#include <cstring>
using namespace std;
void out(int n[2][10]);
void fillit(int n[2][10]);
int main(){
int nums[2][10];
fillit(nums);
out(nums);
}
void fillit(int n[2][10]){
n[0][0] = 1;
n[1][0] = 0;
for (int i = 1; i < 10; i++){
n[0][i] = n[0][i-1] + 2;
n[1][i] = n[0][i-1] + 2;
}
}
void out(int n[2][10]){
for (int r = 0; r <= 1; r++){
for (int c = 0; c <= 9; c++){
cout << n[r][c];
}
cout << endl;
}
}
怎么樣,它更短?
int nums[2][10];
for (int i = 0; i < 20; i++)
{
nums[(i%2)^1][i/2] = i;
}
我注意到第二個數組元素是偶數,而第一個數組對應的元素是一個更大的(因此是奇數)...因此,此答案僅使用加法完成。 可能更容易理解。
void fillit(int n[2][10])
{
int even = 0; // start value
for (size_t i = 0; i < 10; i++)
{
int odd = even + 1;
n[0][i] = odd;
n[1][i] = even;
even += 2;
}
}
我注意到您用C ++標記了此問題。 也許您應該嘗試使用向量。
對於小向量,您只需在大括號中聲明初始值,即可輕松定義矩陣極限[2]和[10]。 在此示例中,我使用易於識別的值進行了初始化,因此您可以知道2x10矩陣尚未填充。 沒有此初始化,包含的值將是隨機噪聲。
std::vector<std::vector<int>> n {
{ 11, 12, 13, 14, 15, 16, 17, 18, 19, 20 }, // row 1
{ 21, 22, 23, 24, 25, 26, 27, 28, 29, 30 } // row 2
// 1 2 3 4 5 6 7 8 9 10 <-- col
};
是的,您可以輸入輸出的目標值,但是不需要fillit()。
要將2x10向量傳遞給fillIt(),請記住您需要將矩陣標記為參考。 以下重點說明n [0]包含奇數,n [1]包含10個偶數。
// vector x vector v--reference
void fillIt(std::vector<std::vector<int>>& n)
{
int even = 0;
for (size_t c = 0; c < 10; ++c) // row major {
int odd = even + 1;
n[0][c] = odd;
n[1][c] = even;
even += 2;
}
}
為了進行測試,我建議僅將2x10向量傳遞給新函數“ showIt()”。
// do not modify--vvvvv do not copy--v
void vec2x10Show (const std::vector<std::vector<int>>& n)
{
// header
std::cout << "\nCOL->";
for (int i=0; i<10; ++i) std::cout << std::setw(3) << i+1 << " ";
std::cout << "\nr1: "; // r c
for (int c=0; c<10; ++c) std::cout << std::setw(3) << n[0][c] << " ";
std::cout << "\nr2: "; // r c
for (int c=0; c<10; ++c) std::cout << std::setw(3) << n[1][c] << " ";
std::cout << std::endl;
}
注意每個循環中的硬編碼“ 10”(一個魔術數字)。 使用向量時,不需要這個幻數,因為向量包括此信息(您的下一個分配)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.