รูปแบบเพชรโดยใช้ while loop ใน c ++ [ซ้ำกัน]
Sep 17 2020
ฉันกำลังพยายามพิมพ์รูปแบบเพชรโดยใช้ while loop ใน c ++ ที่อิงตามความยาวของเพชร แต่ฉันไม่ได้รับผลลัพธ์ที่ฉันต้องการดู ดูเหมือนว่าจะมีปัญหาอะไรกับรหัสของฉัน
#include <iostream>
using namespace std;
int main ()
{
cout << "Length of diamond:";
int length = 0;
cin >> length;
length = length/2;
int r = -length;
while (r <= length) {
r++;
int c = -length;
while (c <= length) {
c++;
if (abs (r) + abs (c) == length) cout << ".";
else cout << " ";
}
cout << endl;
}
return 0;
}
คำตอบ
brc-dd Sep 17 2020 at 08:31
ในฐานะที่เป็นแหลมออกโดยจอห์นในความคิดเห็นของเขาปัญหาคือมีการเพิ่มและr cนี่คือรหัสที่แก้ไข:
#include <iostream>
using namespace std;
int main() {
int length, r, c;
cout << "Length of diamond: ";
cin >> length;
cout << '\n';
length /= 2;
r = -length;
while (r <= length) {
c = -length;
while (c <= length) {
if (abs(r) + abs(c) == length)
cout << '.';
else
cout << ' ';
c++;
}
r++;
cout << '\n';
}
return 0;
}
การเรียกใช้ตัวอย่าง :
Length of diamond: 9
.
. .
. .
. .
. .
. .
. .
. .
.
โปรดทราบว่าอาจมีมากกว่าหนึ่งวิธีในการรับเอาต์พุตที่ต้องการ (ตัวอย่างเช่นการทำr = -length - 1แทนr = -lengthเช่นเดียวสำหรับการcแนะนำโดยจู้เพลงในความคิดเห็นของเขา
คำแนะนำ: ทำตัวให้คุ้นเคยกับดีบักเกอร์ของคุณ using namespace std;หลีกเลี่ยงการวาง