使用C ++循环构建三角形

时间:2019-07-09 04:29:58

标签: c++ loops

我正在尝试用用户输入的底边和高度来构建三角形。 如果这些输入的值不同(基数!=高度),程序将陷入困境,并陷入三角形绘制循环中。

我已经尝试过几次修改代码,但是请把我当成编程新手。

//BUILD TRIANGLE//
#include <string>
#include <iomanip>
#include <iostream>

int main()
{
    std::cout << "\nEnter base and height:\n";
    int height{0}; int base{0};
    std::cin >> base >> height;

    std::string bottom(base, '*');
    std::string top = "*";
    int middlerows = height - 1;
    int middlespacechars;
    std::cout << top << std::endl;

    for (middlespacechars = 0; 
         middlerows != 1 || middlespacechars != base - 2; 
         ++middlespacechars, --middlerows) {

        std::string middlespace(middlespacechars, ' ');
        std::cout << "*" << middlespace << "*\n";
    }

    std::cout << bottom << "\n" << std::endl;
    std::cout << "^TRIANGLE\n";
    std::cout << "BASE = " << base << std::endl;
    std::cout << "HEIGHT = " << height << std::endl;
    std::cout << "goodbye" << "\n" << std::endl;
}

输出完全是杂草丛生,屏幕上的星号没有明显的形状。 但是,当我输入base = height的值时,会弹出一个相当小的直角三角形。

2 个答案:

答案 0 :(得分:2)

使用您的代码,您只能绘制base等于height的正三角形。

如果您在for循环中更改停止条件,则可以获得您可能想要得到的东西:

for (middlespacechars = 0; middlerows != 1 || middlespacechars != base - 2; ++middlespacechars, --middlerows) {

... into ...

for (middlespacechars = 0; middlerows > 1 || middlespacechars < base - 2; ++middlespacechars, --middlerows) {

如果baseheight不同,很有可能无法达到停止条件。如果middlerows1,而middlespacecharsbase - 2,则代码中的for循环将停止。

对其进行测试 here

答案 1 :(得分:0)

//C++ program to display hollow star pyramid

#include<iostream>
using namespace std;

int main()
{
   int rows, i, j, space;

   cout << "Enter number of rows: ";
   cin >> rows;

   for(i = 1; i <= rows; i++)
   {
      //for loop to put space in pyramid
      for (space = i; space < rows; space++)
         cout << " ";

      //for loop to print star
      for(j = 1; j <= (2 * rows - 1); j++)
      {
         if(i == rows || j == 1 || j == 2*i - 1)
            cout << "*";
         else
            cout << " ";
      }
      cout << "\n";
   }
   return 0;
}

OUTPUT: