【发布时间】:2018-04-20 07:41:30
【问题描述】:
我有一个程序可以接收具有权重值的人的金字塔,并且应该使用递归函数来添加该人所支持的两个人的权重(如果该人位于金字塔的边缘,他们仅支持一个人的重量我包括一个图片包我没有很好地解释这一点)并将其添加到它自己的重量值中。我目前遇到的问题只是函数本身只接受二维数组的第一个值而不是所有值?
代码:
#include <stdio.h>
void weight(float x[100][100],int y, int z,int b)
{
if(z==0&&y==0)
{
printf("%.2f\n",x[y][z]);
weight(x,y+1,z,b);
return;
}
if(z==0&&y==b)
{
printf("%.2f",x[y][z]);
x[y][z]+=x[y-1][z];
printf("%.2f",x[y][z]);
}
if(z==0&&y!=b)
{
x[y][z]+=x[y-1][z];
printf("%.2f",x[y][z]);
weight(x,y+1,z,b);
}
if(y==z&&y==b)
{
printf("%.2f",x[y][z]);
x[y][z]+=x[y-1][z-1];
return;
}
if(y==z&&y!=b)
{
x[y][z]+=x[y-1][z-1];
printf("%.2f\n",x[y][z]);
weight(x,y+1,0,b);
}
if(y!=z)
{
printf("%.2f",x[y][z]);
x[y][z]+=x[y-1][z]+x[y-1][z-1];
}
}
int main()
{
//Initialize Variables for use within the program
int bottom;
int input;
int counter=0;
printf("How many people are in the bottom row of your pyramid: ");
scanf("%d",&bottom);
//Initializes pyramid array at correct length
float pyramid[bottom][bottom];
//Takes in all user given input values for pyramid weights
for(int i=0;i<bottom;i++)
{
for(int j=0;j<=i;j++)
{
printf("Please input the weight of person #%d: ",++counter);
scanf("%f",&pyramid[i][j]);
}
}
//Prints out all weight values based on user given input
printf("Pyramid before weight distribution\n");
for(int i=0; i<bottom;i++)
{
for(int j=0;j<=i;j++)
{
printf("%.2f ",pyramid[i][j]);
}
printf("\n");
}
//Prints out all weight values after supporting weight values have been added thru recursive function
printf("Pyramid after weight distribution\n");
weight(pyramid,0,0,bottom-1);
return 0;
}
【问题讨论】:
-
你能解释一下“函数本身只接收二维数组的第一个值而不是所有值”是什么意思吗?
-
我认为您不应该更改二维数组中的值。相反,从
weight()函数返回一个值。 -
float pyramid[bottom][bottom]和float x[100][100]不匹配(如果bottom != 100)。 -
“不匹配”是什么意思?能举个例子吗?
-
您将第一个数组元素的索引(y 和 z)传递给函数 weight,但 weight 不会修改这些值来索引数组中的其他元素。
标签: c arrays function multidimensional-array