C++ 如何在c++;
二,* 四,** 六,*** 需要输出以上模式 下面给出的代码我已经尝试过了C++ 如何在c++;,c++,loops,C++,Loops,二,* 四,** 六,*** 需要输出以上模式 下面给出的代码我已经尝试过了 #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; } #包括 #包括
#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;
}
#包括
#包括
使用名称空间std;
int main(){
字符串星=“*”;
INTA=2;
而(a您可以添加第二个循环来处理星星
cout<<a;
for (int i = 0; i < a/2; i++)
cout<<'*';
cout<<endl;
cout最简单的方法可能是
#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;
}
#包括
#包括
使用名称空间std;
int main(){
INTA=2;
而(a#包括
#包括
int main(){
对于(auto i=1;i,您的代码应该产生编译错误,如下所示:
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;
~~~~^~~~~~
输出:
2*
4**
6***
试试这个:
while(a <= 6){
cout<<a;
int c = 0;
int b = a/2;
while(c < b){
cout<<star<<endl;
c++;
}
a=+2;
}
while(你认为那颗星是什么?)
应该这样做??你必须用a/2
'*'
字符写一个循环或初始化一个std::string
,这样才能工作。你计算应该打印的星星数的逻辑是正确的。但是打印那么多星星的方法是不正确的。你将如何打印一个星星?@user0042-如果OP来了g来自Python、Javascript或Perl之类的语言?很容易犯错误。std::string
有一个使用单个字符和数字的构造函数。需要在loop@gihansalith然后用这个想法,用whileInteresting的方法写下你自己的循环,很好!我打赌在看到这个之后我是否应该删除我的答案..你怎么看?
2*
4**
6***
while(a <= 6){
cout<<a;
int c = 0;
int b = a/2;
while(c < b){
cout<<star<<endl;
c++;
}
a=+2;
}