我刚刚完成了这个帕斯卡三角形项目,输出不是一个正确的三角形,任何人都知道为什么会这样,间距看起来很正确,只是对齐方式偏离了
#include <string>
#include <iostream>
using namespace std;
int factorial(int numPar); //the factorial function will recieve a number, and return that number's factorial
int pascalNum(int rowPar, int elementPar);
int main(){
//declarations
string strOutput = "";
int userNum;
int rowCounter = 0;
int elementCounter = 0;
int columnsPerRow = 1;
int spaces;
int initialSpaces;
int counter = 0;
//get user input
cout << "Enter an integer from 1 to 10: ";
cin >> userNum;
while (userNum > 10 || userNum < 1){
cout << "Invalid entry: " << endl;
cin >> userNum;
}
initialSpaces = userNum + 4; //needed to make the triangle an isoscoles, and keep it away from left
//calculations
while ((rowCounter + 1) <= userNum){
for (counter = initialSpaces; counter > 0; counter--){
strOutput = strOutput + " ";
}
while (elementCounter < columnsPerRow){
strOutput = strOutput + to_string(pascalNum(rowCounter, elementCounter));
if (pascalNum(rowCounter, elementCounter) < 10){
spaces = 3;
}
else if (pascalNum(rowCounter, elementCounter) < 100){
spaces = 2;
}
else if (pascalNum(rowCounter, elementCounter) < 1000){
spaces = 1;
}
while (spaces > 0){
strOutput = strOutput + " ";
spaces = spaces - 1;
}
elementCounter = elementCounter + 1;
}
cout << strOutput << endl;
columnsPerRow = columnsPerRow + 1;
elementCounter = 0;
rowCounter = rowCounter + 1;
//initialSpaces--; //this makes there be less and less space until the triangle starts
strOutput = "";
}
system("pause>nul");
return 0;
}
int factorial(int numPar) {
//declarations
int counter = 1;
int numResult = 1;
int initial = numPar;
if (numPar > 1){
while (counter <= numPar){
numResult = numResult * counter;
counter++;
}
return numResult;
}
else
return 1;
}
int pascalNum(int rowPar, int elementPar){
int answer;
answer = factorial(rowPar) / (factorial(elementPar) * factorial(rowPar - elementPar));
return answer;
}