使用循环插入一系列数字 [英] Inserting a sequence of numbers using loop

查看:89
本文介绍了使用循环插入一系列数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好,



我在1年内编程很新,几天前我开始学习c ++,只需要帮助就可以了解这段代码



  #include   <   iostream  >  

使用 命名空间标准;

int main()
{
int i = 0 ,j = 0 ;
int a [i] [j];

// 用于插入数字序列的循环
的类=code-keyword>(i = 0 ; i< 3; i ++)
{
int k = 1 ;
for (j = 0 ; j< 3; j ++)
{
A [i] [j] = K;
k ++;
}
}

// 用于打印内容的循环数组
for (i = 0 ; i< 3; i ++)
{
for (j = 0 ; j< 3; j ++)
{
cout<< a [i] [j]<< endl;
}
}

返回 0 ;
}





预期输出: - 123456789

解决方案

而不是:

  //  用于插入序列的循环数字 
for (i = 0 ; i< 3; i ++)
{
int k = 1 ;
for (j = 0 ; j< 3; j ++)
{
A [i] [j] = K;
k ++;
}
}



试试这个:

  //  用于插入数字序列的循环 
int k = 1 ;
for (i = 0 ; i< 3; i ++)
{
for (j = 0 ; j< 3; j ++)
{
A [i] [j] = K;
k ++;
}
}



每次启动内循环(在j变量上执行3步后),重置k的值因此,你可能得到123123123而不是123456789.



编辑:你的代码的另一个问题:声明数组时你必须使用编译时常量来指定数组维度,你不能使用变量的值:

  int  i =  0 ,j =  0 ; 
int a [i] [j];
// 数组声明应更改为例如
int a [ 3 ] [ 3 ];


Hello guys,

Im quite new to programming in my 1 year and i started learning c++ few days ago and just need help in this code

#include <iostream>

using namespace std;

int main()
{
    int i=0,j=0;
    int a[i][j];

    //loop for inserting sequence of numbers
    for(i=0;i<3;i++)
    {
        int k=1;
        for(j=0;j<3;j++)
        {
            a[i][j]=k;
            k++;
        }
    }

    //loop for printing the contents of array
    for(i=0;i<3;i++)
    {
        for(j=0;j<3;j++)
        {
            cout<<a[i][j]<<endl;
        }
    }

    return 0;
}



Expected Output:- 123456789

解决方案

Instead of this:

//loop for inserting sequence of numbers
for(i=0;i<3;i++)
{
    int k=1;
    for(j=0;j<3;j++)
    {
        a[i][j]=k;
        k++;
    }
}


try this:

//loop for inserting sequence of numbers
int k=1;
for(i=0;i<3;i++)
{
    for(j=0;j<3;j++)
    {
        a[i][j]=k;
        k++;
    }
}


Everytime you start the inner loop (after 3 steps on the j variable) you reset the value of k to 1. For this reason you probably get 123123123 instead of 123456789.

EDIT: Another problem with your code: when declaring the array you must use compile time constants to specify the array dimensions, you can not use the value of variables:

int i=0,j=0;
int a[i][j];
// array declaration should be changed for example to
int a[3][3];


这篇关于使用循环插入一系列数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆