我正在設計一個C++類的程序,我正在使用,教授希望我們製作一個使用「*」輸出菱形的程序。我堅持的是我的程序輸出太多的行。爲什麼我的循環執行得太頻繁?
而不是
*
***
*
它輸出
*
***
*****
***
*
我將如何修改我的代碼得到這個工作?我一直在網上尋找答案,整個上午都沒有運氣。
這裏是我的代碼:
#include <iostream>
using namespace std;
int main() {
//Define Varaible
int N;
cout << "Please enter a postitive integer: ";
cin >> N;
cout << "Here is your diamond." << endl << endl;
for (int i = 0; i <= 2 * N; i++) {
for (int j = 0; j <= 2 * N; j++) {
if (i <= N) {
if (j < N - i || j > N + i) {
cout << ' ';
}
else {
cout << '*';
}
}
else {
if (j < i - N || j > 3 * N - i) {
cout << ' ';
}
else {
cout << '*';
}
}
}
cout << endl;
}
return 0;
}
有了什麼輸入,你會得到那些「錯誤」的圖像?如果你得到1行太多並且不理解你自己的代碼(...?),添加「N = N-1;」某處。 – usr2564301