2017-08-28 41 views
-6

2 *如何打印炭在C++中多次

4 **

6 ***

需要上述图案 代码输出下面给出我曾尝试

#include <iostream> 
#include<string> 

using namespace std; 

int main(){ 
string star = "*"; 
int a=2; 
while(a<=6){ 
    cout<<a<<star*(a/2)<<endl; 
    a+=2; 
} 
return 0; 
} 
+2

你认为'star *(a/2)'应该做什么?你必须编写一个循环或用'a/2'''*''字符初始化一个'std :: string'来实现这个功能。 – user0042

+0

您的计算应该打印的恒星数量的逻辑是正确的。但是打印这些明星的方法并不正确。你会如何打印一颗星星? – sameerkn

+1

@ user0042 - 如果OP来自Python,Javascript或Perl之类的语言?容易犯错。 – StoryTeller

回答

2

最简单的方法可能是

#include <iostream> 
#include<string> 

using namespace std; 

int main(){ 
    int a=2; 
    while(a<=6){ 
     cout<< a << std::string((a/2),'*') <<endl; 
       // ^^^^^^^^^^^^^^^^^^^^^^ 
     a+=2; 
    } 
    return 0; 
} 
+0

有趣的方法,很好!我敢打赌,看到这个消息后我是否应该删除我的答案。你觉得怎么样? – gsamaras

0

您可以添加第二个循环来处理星星。

cout<<a; 
for (int i = 0; i < a/2; i++) 
    cout<<'*'; 
cout<<endl; 
+0

需要使用while循环 – gihansalith

+1

@gihansalith然后使用这个想法并编写自己的循环使用,而 –

3
#include <iostream> 
#include<string> 

int main() { 
    for(auto i=1;i<=3;i++) 
    { 
     std::cout << i*2 << std::string(i,'*') << '\n'; 
    } 
    return 0; 
} 
0

您的代码应该产生一个编译错误,像这样:

prog.cc: In function 'int main()': 
prog.cc:10:22: error: no match for 'operator*' (operand types are 'std::__cxx11::string {aka std::__cxx11::basic_string<char>}' and 'int') 
     cout<<a<<star*(a/2)<<endl; 
        ~~~~^~~~~~ 

因为star是一个字符串,a整数,因此你不能做你想做的事情。

相反,您可以不使用std::string,而是使用单个字符。然后使用循环根据需要多次打印星星(您似乎知道循环应该执行多少次)。

代码:

#include <iostream> 

using namespace std; 

int main(){ 
    char star = '*'; 
    int i, a = 2; 
    while(a <= 6) { 
     cout << a; 
     i = 0; 
     while(i++ < a/2) 
      cout<< star; 
     cout << endl; 
     a+=2; 
    } 
    return 0; 
} 

输出:

2* 
4** 
6*** 
0

试试这个:

while(a <= 6){ 

cout<<a; 

int c = 0; 
int b = a/2; 

while(c < b){ 

    cout<<star<<endl; 
    c++; 

} 
a=+2; 
} 

这是我能回答很简单。希望你能明白这个主意。