【问题标题】:print stars as much as the values in the array打印星星与数组中的值一样多
【发布时间】:2014-05-14 15:11:56
【问题描述】:

我正在尝试让 C++ 程序开始创建一个数组并从用户那里获取值,然后打印每个值 + 星号,尽可能多的值是 .. 示例:用户输入了 5,那么输出必须像这 5***** 输入

1

2

3

4

5

6

输出

1*

2**

3***

4**** 等等

..帮助:(

#include <iostream> 
using namespace std; 
void main() 
{
    int arr[10]; 
    for (int i = 0; i < 10; i++)
    {
        cin >> arr[i]; 
        int x = arr[i]; 
        for (int j = 0; x <= arr[i]; j++)
        {
            cout<< "*";
        }
    }
}

还有一个帮助,请你给我一些有用的链接来练习编程以变得专业

【问题讨论】:

  • 在将“打印五颗星”部分与数组和输入循环纠缠之前,您应该已经完善了它。 独立开发新功能。
  • 当您遇到问题时,始终建议您说明您得到了什么以及您期望什么,而不是让人们为您解释您的代码。
  • x &lt;= arr[i] -> j &lt; arr[i] ?

标签: c++ arrays nested-loops


【解决方案1】:

您的代码错误。使用以下代码:

#include <iostream> 
using namespace std; 
int main()  {
  int arr[10]; 
  for (int i = 0; i < 10; i++)
  {
   cin >> arr[i]; 
   int x = arr[i]; 
   for (int j = 0; j < x; j++){ // your condition was wrong

   cout<< "*";
  }
   cout<<endl; // for better formatting
 }
 return 0;
}

对于已编辑的问题

int main()  {
int arr[10];
for (int i = 0; i < 10; i++)
{
    cin >> arr[i];


}
for (int i = 0; i < 10; i++)
{
    int x = arr[i];
    cout << x;
    for (int j = 0; j < x; j++){ // your condition was wrong

        cout << "*";
    }
    cout << endl;
}

return 0;
} 

【讨论】:

  • o sorry man 程序必须是这样输入 1 2 3 4 5 6 7 ,然后像这样打印 1* next line 2** next line 3*** 等等,,先取然后打印所有值
  • int main() 也可能需要修复。至少 clang++ 不喜欢 void。
  • @JoachimIsaksson,你是对的。 void main 不是可移植的,也是不好的做法。已编辑。
  • 输入 1 2 3 4 5 6 输出 1* 2** 3*** 4**** 等等
【解决方案2】:



#include <iostream> 
using namespace std; 
void main() 
{
    int nbValues = 10;
    int arr[nbValues];

    // First recover the values
    for (int i = 0; i < nbValues; i++)
    {
        cin >> arr[i];
    }

    // Then print the output
    for (int i = 0; i < nbValues; i++)
    {
        int x = arr[i];
        cout << x;// Print the number
        for (int j = 0; j < x; j++)
        {
            cout<< "*";// Then print the stars
        }
        cout << endl;// Then new line
    }
}

【讨论】:

    猜你喜欢
    • 2023-03-28
    • 2015-07-16
    • 2018-08-26
    • 1970-01-01
    • 1970-01-01
    • 2012-05-19
    • 1970-01-01
    • 2021-07-30
    • 1970-01-01
    相关资源
    最近更新 更多