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 *如何打印炭在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;
}
最簡單的方法可能是
#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;
}
有趣的方法,很好!我敢打賭,看到這個消息後我是否應該刪除我的答案。你覺得怎麼樣? – gsamaras
您可以添加第二個循環來處理星星。
cout<<a;
for (int i = 0; i < a/2; i++)
cout<<'*';
cout<<endl;
需要使用while循環 – gihansalith
@gihansalith然後使用這個想法並編寫自己的循環使用,而 –
#include <iostream>
#include<string>
int main() {
for(auto i=1;i<=3;i++)
{
std::cout << i*2 << std::string(i,'*') << '\n';
}
return 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***
試試這個:
while(a <= 6){
cout<<a;
int c = 0;
int b = a/2;
while(c < b){
cout<<star<<endl;
c++;
}
a=+2;
}
這是我能回答很簡單。希望你能明白這個主意。
你認爲'star *(a/2)'應該做什麼?你必須編寫一個循環或用'a/2'''*''字符初始化一個'std :: string'來實現這個功能。 – user0042
您的計算應該打印的恆星數量的邏輯是正確的。但是打印這些明星的方法並不正確。你會如何打印一顆星星? – sameerkn
@ user0042 - 如果OP來自Python,Javascript或Perl之類的語言?容易犯錯。 – StoryTeller