有这样一个程序
#include <bits/stdc++.h>
using std::cout;
using std::endl;
using std::string;
int main()
{
const int n = 15;
for(int i=0;i<n;i++)
cout << string(n/2-1-i, ' ') << string(i*2+1, 42) << endl;
return 0;
}
但是在这个过程中,它抛出了一个异常。摆脱它或在另一个上编写程序的方法是什么。
*
***
*****
*******
*********
***********
*************
terminate called after throwing an instance of 'std::length_error'
what(): basic_string::_S_create
最佳答案
n/2-1-i
当n=15
且i >= 7
时为负数,因为n/2 == 7
。因此您的程序需要重新设计。
编辑:
只需更改一行:
cout << string(n-i-1, ' ') << string(i*2+1, 42) << endl;
关于c++ - 如何打印N个相同的字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28353750/