简体   繁体   English

C ++递归函数,用于打印不起作用的标尺。

[英]C++ Recursive function for printing a ruler not working.

I've been trying to teach myself C++ from a book. 我一直试图从一本书中教自己C ++。 The following piece of code has been a problem, as I can't figure out what I'm doing wrong.The code is an example from the book, and yet it won't bring the same result. 以下代码是一个问题,因为我无法弄清楚自己在做什么错。代码是本书中的一个示例,但不会带来相同的结果。

The function subdivide() is supposed to use the divide and conquer method for dividing the array at midpoint and printing the character '|' 函数subdivide()应该使用分而治之的方法来在中点分割数组并打印字符'|'。 there(creating an illusion of a ruler), with subsequent mid-point printing at every new line. 在那里(给人一种尺子的错觉),随后在每个新行上打印中点。 The problem is, the final print contains only the character '|' 问题是,最终的印刷品仅包含字符“ |” at the end-points in all the lines, and no character is printed in the middle. 在所有行的端点,中间没有字符打印。

I tried to post an image, but apparently I can't. 我试图发布图片,但显然不能。

I'll appreciate any help. 我将不胜感激。 Here's the C++ code: 这是C ++代码:

//using recursion to subdivide a ruler
#include<iostream>
const int len=66;
const int div=6;
void subdivide(char ar[], int min,int max,int level);

int main()
{
using namespace std;
    char ruler[len];
    int i;
    for(int i=1; i<(len-2); i++)
        ruler[i]=' ';
    ruler[len-1]='\0';

    int min=0;
    int max=len-2;
    ruler[min]=ruler[max]='|';

    cout<<ruler<<endl;

    for(i=1;i<=div;i++){
        subdivide(ruler, min, max, i);
        cout<<ruler<<endl;
          for(int j=1; j<len-2; j++)
                ruler[j]=' ';
    }

return 0;
}

void subdivide(char ar[],int low,int high,int level)
{
using namespace std;
if (level==0);
    return;
int mid=(high+low)/2;
ar[mid]='|';
subdivide(ar, low, mid, level-1);
subdivide(ar, mid, high, level-1);
}

In your subdivide function, you have a semicolon after the if: subdivide函数中,if后面有分号:

if (level==0);
    return;

The indentation is deceiving, and what your code is actually doing is 缩进是骗人的,您的代码实际在做什么

if (level==0);  //does nothing
return; // always returns (before modifying the ruler)

Change it to 更改为

if (level==0)    //no semicolon here
    return;

I got the output as shown in the pic. 我得到的输出如图所示。 Is this not you want ? 这不是你想要的吗? Remove the semicolon at if ( level == 0) if ( level == 0)处删除分号

在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM