[英]How to print N identical characters
There is such a program 有这样的程序
#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;
}
But in the process, it throws an exception. 但是在此过程中,它将引发异常。 What are the ways to get rid of it or to write a program on another. 有什么方法可以摆脱它或在另一个程序上编写程序。
*
***
*****
*******
*********
***********
*************
terminate called after throwing an instance of 'std::length_error'
what(): basic_string::_S_create
n/2-1-i
will be negative when n=15
and i >= 7
, because n/2 == 7
. 当n=15
并且i >= 7
, n/2-1-i
将为负,因为n/2 == 7
。 So a redesign is needed for your program. 因此,您的程序需要重新设计。
EDIT: 编辑:
Just one line to change: 只需更改一行:
cout << string(n-i-1, ' ') << string(i*2+1, 42) << endl;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.