我写了一个代码,用星号打印一个数字 - 无论是负数还是正数。我的程序从用户的输入中反转数字,然后将其切成数字逐个打印,但不在同一行。这是我的代码:
#include <iostream>
using namespace std;
int main() {
int n, i = 0, reverse = 0, digit;
cout << "Enter an integer:";
cin >> n;
cout << endl;
if(n < 0){
cout << "--"<<endl;
n = n - 2*n;
}
while(n > 0){
reverse = reverse*10 + n%10;
n = n / 10;
}
while(reverse > 0){
digit = reverse % 10;
reverse = reverse / 10;
if(digit == 0){
cout << "***"<<endl;
cout << "* *"<<endl;
cout << "***"<<endl;
cout << endl;
}
if(digit == 1){
cout << " * "<<endl;
cout << "** "<<endl;
cout << "***"<<endl;
cout << endl;
}
if(digit == 2){
cout << "** "<<endl;
cout << " * "<<endl;
cout << " **"<<endl;
cout << endl;
}
if(digit == 3){
cout << "***"<<endl;
cout << " **"<<endl;
cout << "***"<<endl;
cout << endl;
}
if(digit == 4){
cout << "* *"<<endl;
cout << "***"<<endl;
cout << " *"<<endl;
cout << endl;
}
if(digit == 5){
cout << " **"<<endl;
cout << " * "<<endl;
cout << "** "<<endl;
cout << endl;
}
if(digit == 6){
cout << "* "<<endl;
cout << "***"<<endl;
cout << "***"<<endl;
cout << endl;
}
if(digit == 7){
cout << "***"<<endl;
cout << " *"<<endl;
cout << " *"<<endl;
cout << endl;
}
if(digit == 8){
cout << "***"<<endl;
cout << "***"<<endl;
cout << "***"<<endl;
cout << endl;
}
if(digit == 9){
cout << "***"<<endl;
cout << "***"<<endl;
cout << " *"<<endl;
cout << endl;
}
}
}
我很好奇,如果有任何可能的方法来打印同一行中的数字,或者如果没有任何数字,是否可以使用固定的数字,例如:3位数字或4-数字? 附:如果有任何简单的方法(仅使用循环,当然(if-else))不要写完整代码,只写一个提示。
答案 0 :(得分:1)
您需要的变量: digCount:你有多少位数, digits [digCount]:数字计数大小的int数组。
设置变量和:
从0到digCount循环。在这个循环中,首先写入所有数字的顶部,然后是中间,最后是底部。显示我的意思:
认为你有879:
for(int i = 0; i < digCount; i++)
{
cout<< topofDigit[i] << \t;
}
cout << "\n";
for(int i = 0; i < digCount; i++)
{
cout<< middleofDigit[i] << \t;
}
cout << "\n";
for(int i = 0; i < digCount; i++)
{
cout<< bottomofDigit[i] << \t;
}
cout << "\n";
我希望它能给你一个意见。为了说明更多,该程序将首先编写:
*** *** ***
Then:
*** * ***
And finally:
*** * *
Final output:
*** *** ***
*** * ***
*** * *
答案 1 :(得分:0)
这是提示,而不是直接打印星号,尝试使用std::string
(或char数组)
例如,这是我存储星形的方式:
s[0][0]="***";
s[0][1]="* *";
s[0][2]="***";
然后使用for
迭代s
,这样您就可以打印所有数字的第一行,然后是第二行,然后是第三行。
答案 2 :(得分:0)
不是一次打印三行而是逐行打印。对于每个数字打印只是第一行(中间有空格)。然后重复中间和最后一行的过程。只有在线结束后才打印endl。
因此,我们需要首先以有效的方式指定数组的外观。我们将创建char数组。
char top_line[10][4] = {"***", " *", "** ", "***", "* *", " **", "* ", "***", "***", "***" };
char middle_line[10][4] = {"* *", " *", " * ", " **", "***", " * ", "***", " *", "***", "***" };
char bottom_line[10][4] = {"***", " *", " **", "***", " *", "** ", "***", " *", "***", " *" };
cout <<"Enter a number:";
int n;
cin >> n;
int n_copy = n;
// We count the number of digits in n;
int digits = 1;
while(n) {
n/=10;
digits *= 10;
}
digits = digits/10;
n = n_copy;
stringstream line1, line2, line3;
while (n) {
int d = n / digits;
n = n % digits;
digits /= 10;
line1 << top_line[d] << " ";
line2 << middle_line[d] << " ";
line3 << bottom_line[d] << " ";
}
cout << line1.str() << endl << line2.str() << endl << line3.str() << endl;
演示:Ideone