这是我的C ++作业问题:
以下算法是使用嵌套循环显示菱形图案的问题的解决方案。将下面的算法转换为C ++程序。构建,运行和测试程序。
算法解决方案:
开始
Declare numRows as constant integer = 7
Declare maxPlus as constant integer = 7
Declare numSpaces as integer
Declare numPluses as integer
Declare row as integer
Declare space as integer
Declare plus as integer
Set row = 1
Repeat while row >= 1 AND row <= numRows
Set numPluses = 2 * row - 1
if(numPluses > maxPlus) then
Set numPluses = 14 - numPluses
endif
Set numSpaces = (maxPlus - numPluses) / 2
Set space = 1
Repeat while space >= 1 AND space <= numSpaces
Display( ' ')
Set space = space + 1
End Repeat
Set plus = 1
Repeat while plus >= 1 AND plus <= numPluses
Display( '*')
Set plus = plus + 1
End Repeat
Set row = row + 1
Display a new line
End Repeat
停止
我的代码:
#include <iostream>
using namespace std;
int main() {
const int numRows = 7;
const int maxPlus = 7;
int numSpaces;
int numPluses;
int row;
int space;
int plus;
row = 1;
while((row >=1) && (row <= numRows)){
numPluses = 2 * row - 1;
if(numPluses > maxPlus){
numPluses = 14 - numPluses;
}
numSpaces = (maxPlus - numPluses)/ 2;
space = 1;
while((space >= 1) && (space <= numSpaces)){
cout << " ";
space++;
}
while((plus >= 1) && (plus <= numPluses)){
cout << "*";
plus++;
}
row++;
cout << endl;
}
return 0;
}
我的问题是为什么我没有获得钻石图案?我觉得我正确地翻译了算法,但我得到的只是一堆空白。我是否错误地阅读了问题或者我的代码是错误的? screenshot of C++ code
答案 0 :(得分:5)
在最后一次while循环之前:
Set plus = 1
你在翻译中错过了。
答案 1 :(得分:1)
代码未初始化plus
。
有一种习惯可以挽救很多悲伤。永远不要声明变量而不在定义点给它一个有意义的初始值。将变量的范围限制在实际使用的位置。翻译伪代码时,这意味着可以进行一些重写。 Diggit。
int main() {
const int numRows = 7;
const int maxPlus = 7;
for (int row = 1; row <= numRows; ++row) {
const int trianglePluses = 2 * row - 1;
const int numPluses = trianglePluses <= maxPlus
? trianglePluses
: 2 * numRows - trianglePluses;
const int numSpaces = (maxPlus - numPluses) / 2;
for(int space=1; space <= numSpaces; ++space) {
cout << " ";
}
for (int plus = 1; plus <= numPluses; ++plus) {
cout << "*";
}
cout << endl;
}
return 0;
}