[英]how to make this number shape?
編寫一個程序來顯示下面的 n 行模式,其中 n 的范圍在 1 到 100 之間。變量 n 應該由用戶輸入。 如果用戶輸入在 1 到 100 之間,則 output 金字塔如下所示,否則提示用戶再次輸入 n。
這是示例 output: 輸入行數:6
1
2 3
3 4 5
4 5 6 7
5 6 7 8 9
6 7 8 9 10 11
這是我的代碼,它顯示了一個接近的答案,但不正確。
int num=1 , counter=1;
cout << "Enter the number of rows: " ;
cin>>num;
for(int i=0;i<=num;i++)
{
for(int j=0;j<=i;j++)
{
cout<<counter<<" ";
counter++;
}
cout<<endl;
}
int num = 1, counter = 1, temp = 1;
cout << "Enter the number of rows: ";
cin >> num;
for (int i = 0; i < num; i++)
{
for (int j = 0; j <= i; j++)
{
cout << temp << " ";
temp++;
}
counter++;
temp = counter;
cout << endl;
}
變量 temp 用作行的計數器,同時變量 counter 負責第一列中的起始編號。
您應該在每次運行外部循環中設置counter
,就在進入內部循環之前使用counter = i+1
之類的東西,您編寫此變量的此代碼值的方式將延續到下一次迭代並繼續向上。
另一種解決方案是打印j
並在內部循環上工作,然后它應該以i
開頭,第一個不合格的數字將是2*i
這樣i
等於2
序列將是2 3
,
無論哪種方式,您還應該重新設計您的外部循環,因為現在它以 0 開始並以num
結束,這意味着它經歷了num+1
次迭代
int rows, i, j = 0, number = 0, counter = 0;
cout << "Enter the number of rows: ";
cin >> rows;
for (i = 1; i <= rows; i++)
{
while (j != 1 * i)
{
if (counter <= rows)
{
cout << i+j << " ";
counter++;
}
++j;
}
number=counter=j=0;
cout << endl;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.