问题描述
我一直试图从一本书中教自己C ++.以下代码是一个问题,因为我无法弄清楚自己在做什么.代码是本书中的一个示例,但不会带来相同的结果.
I've been trying to teach myself C++ from a book. 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.
函数subdivide()应该使用分而治之的方法来在中点分割数组并打印字符'|'.在那里(给人一种尺子的错觉),随后在每条新行上进行中点打印.问题是,最终的印刷品仅包含字符"|"在所有行的端点,中间没有字符.
The function subdivide() is supposed to use the divide and conquer method for dividing the array at midpoint and printing the character '|' 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.
我将不胜感激.这是C ++代码:
I'll appreciate any help. Here's the C++ code:
//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);
}
推荐答案
在您的 subdivide
函数中,if后面有分号:
In your subdivide
function, you have a semicolon after the 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)
将其更改为
if (level==0) //no semicolon here
return;
这篇关于C ++递归函数,用于打印不起作用的标尺.的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!