簡體   English   中英

C ++和數組中的嵌套循環

[英]Nested loops in c++ and arrays

我正在用C ++編寫該程序,無法確定我在做什么錯。 這個嵌套循環應該打印一個包含行和列的矩陣,並且由於某種原因,在詢問用戶輸入時,它會卡在行0和列0上。 提前致謝。

#include <iostream>
using namespace std;
int main ()
{
    //program to print the input values in rows and columns of two dimensional array in revserse roder using loop
    //decalre the vraibles and array
    int array [3][3],rows,cols,maxrows = 3,maxcols = 3;
    //use for loop to intiiate the array and input values from users
    for (rows = 0; rows < maxrows;rows = rows++ )
    {
        for (cols = 0; cols < maxcols;cols = cols++ )
        {
            cout  << " Enter the value for array location : " << " [ " << rows << " , " << cols << " ] " ;     
            cin >> array [rows][cols] ;
        }
    }
    //display the values entered in array starting with bottom row first and then the rest
    for ( rows = 0 ; rows < maxrows ; rows ++ )
    {
        for ( cols = 0 ; cols < maxcols ; cols ++ )
        {
            cout << " The values that were entered in this array starting with bottom row are " << array [rows][cols] ;
        }
    }
}     

注釋暗示了問題,但沒有明確指出:

rows = rows++

之所以含糊不清,是因為獲取分配給左側的值 ,右側會增加。 如果為g ++啟用了適當的警告,則表示

foo.c:26: warning: operation on ‘rows’ may be undefined

實際上,它表示某些編譯器可能會給出不同的結果,例如使其與

rows = rows

如果這樣做,將導致無限循環。 (順便說一下,對於g ++,該值的確會增加)。

您已經有了答案,但是我認為我應該指出變量聲明的樣式。 即, int array [3][3],rows,cols,maxrows = 3,maxcols = 3;

這很不好,因為它不是很可讀。 從最嚴格的意義上說,行和列變量的類型是錯誤的,請參見為什么將size_t用作數組索引時更好。 此外,可以解釋為什么您應該贊成前遞增而不是后遞增,除非您有充分的理由不這樣做(++ i代替i ++),盡管在這種情況下,因為運算符是不超載。 此外,適當地使用常量可使代碼更具可讀性,並消除某些類型的錯誤。 最后,盡快為您的變量提供一個合理的值,以消除不確定的行為。

#include <iostream>
using namespace std;
int main ()
{
    //program to print the input values in rows and columns of two dimensional array in revserse roder using loop
    //decalre the vraibles and array
    int array [3][3] = {};
    const size_t maxrows = 3,
    const size_t maxcols = 3;

    //use for loop to intiiate the array and input values from users
    for (size_t rows = 0; rows < maxrows; ++rows )
    {
        for (size_t cols = 0; cols < maxcols; ++cols )
        {
            cout  << " Enter the value for array location : " << " [ " << rows << " , " << cols << " ] " ;     
            cin >> array [rows][cols] ;
        }
    }
    //display the values entered in array starting with bottom row first and then the rest
    for ( size_t rows = 0; rows < maxrows ; ++rows)
    {
        for ( size_t cols = 0; cols < maxcols ; ++cols)
        {
            cout << " The values that were entered in this array starting with bottom row are " << array [rows][cols] ;
        }
    }
}   

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM