【问题标题】:How to draw a rectangle using a char parameter in C++?如何在 C++ 中使用 char 参数绘制矩形?
【发布时间】:2015-05-09 11:33:08
【问题描述】:

我想使用 C++ 绘制和填充一个矩形。传入的函数参数必须是char,而不是int。在我的头文件中,绘图函数是这样的:

void draw(char);

我的 rectangle.cpp 文件是这样的:

void rectangle::draw(char )
{
    for(height=0;height<=height;height++)
    {
        for(width=1;width<=width;width++)
        {
            cout<<'*';
        }
    }
}

我的 main.cpp 文件是这样的:

rectangle d1;
d1.draw(char);

当我运行程序时,它给了我错误:

'char' 之前的预期主表达式。

我正在使用 Code::Blocks 13.12。有什么想法可以解决这个问题吗?

【问题讨论】:

  • 您的for 循环不正确;尝试一个涉及for 循环的更简单的任务。然后我们可以谈谈如何调用一个函数。
  • 你必须为你的参数命名,即void rectangle::draw(char c)
  • 你必须用那个char c参数做一些事情
  • 我想用 '* ' 用 char 参数填充一个矩形,但我不知道如何使用。在 for 循环中,我必须绘制并填充这个参数中的矩形。我应该在头文件中定义那个 char c='*' 吗?

标签: c++ parameters char drawing


【解决方案1】:

您的平局缺少一个变量。将draw(char); 更改为draw(char c); 并且两个for 循环都需要一个最大范围,而不是与递增变量相同的值。 height&lt;=height;width&lt;=width;

#include <iostream>
using namespace std;


void draw(char c )
{
    int rheight=10;
    int rwidth=20;

    for(int height=0;height<=rheight;height++)
    {
        for(int width=1;width<=rwidth;width++)
        {
            cout<<c;
        }
        cout<<"\n";
    }
}


int main()
{

    draw('*');
    cout<<"\n";

  return 0;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-08-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-06-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多