C - 使用 2D 数组绘制条形图 - 不会绘制负值



大家好,感谢您抽出宝贵时间阅读本文。我正在做一个练习,给我一个整数数组,每个整数代表图表中一个条形的"高度"。负值表示条形延伸到水平轴下方。因此,如果我得到一个包含 4 个整数的数组,图表中正好有 4 个柱线。

我使用了一个 2D 字符数组来尝试完成这个练习。

注意:练习的文本说图形中的每个条形之间应该有两个空格,所以这就是为什么我在每次传递中将j控制变量增加 3 的原因。

我在负值方面遇到问题。无论我做什么,负值都不会在屏幕上打印出来。

我尝试如下:我通过将数组大小乘以 3 来确定图形的宽度。然后,我将 2D 数组的所有字段设置为空格,中间的水平线除外。

外部j循环遍历矩阵的列。我只有一个循环,因为在每次通过j循环时,我们都从第 10 行开始。

K循环实际上执行绘图。循环从零到number-1,在顶部(或底部(为星号留出空间。

我有两个 if 语句检查数字是<0 还是0,因为在这两种情况下,条形应该以不同的方式显示。

这是我的代码:

#include <stdio.h>
int main()
{
char mat[30][40];
int i,j, size=0, m=20, n=40;

int arr[7] = {1,2,-3,4,-5,6,-7};
size=7;
n=size*3; // n is the width of the graph
for(i=0; i<m; i++) {          // I set all fields of the 2D array to spaces
for(j=0; j<n; j++) {      // except for the horizontal line
if(i==10) mat[i][j]='-';
else mat[i][j]=' ';
}
}
int k;
int position=0; // position is the variable I use to iterate through the array
int l;
for(j=0; j<n; j+=3) {
l=10;

for( k = 0; k<arr[position]-1; k++) {
if(arr[position]==0) {
mat[10][j] = '*';    // if the height is zero, put an asterisk
}

else if((arr[position])<0) {
l++;                    // if the number is negative, 
mat[l][j]='|';          // the bar extends below the horizontal line
}                          

else if(arr[position]>0) {
l--;              // if the number is positive, the bar extends above the
mat[l][j] = '|';  // horizontal line
}
}

if(arr[position]>0) mat[l-1][j]='*';  //every bar ends with an asterisk
else if(arr[position]<0) {       
mat[l+1][j]='*';
}

position++;  // jump to the next element in array

}
for(i=0; i<m; i++) {
for(j=0; j<n; j++) {
printf("%c",mat[i][j]);
}
printf("n");
}
return 0;
}

对于负数,它只是不起作用。此外,我还做了一些测试,条件else if((arr[position])<0)永远不会实现,我不知道为什么。它的作用是在水平线下方放置一个星号,但仅此而已。

感谢您的阅读!

问题是这样的:

for( k = 0; k<arr[position]-1; k++)

如果arr[position]小于 2,则不会发生任何事情。试试这个

.
.
.
l=10;
int end = arr[position] < 0 ? -arr[position] : arr[position]; // added code

for( k = 0; k < end - 1; k++) { // changed code
if(arr[position]==0) {
mat[10][j] = '*';    // if the height is zero, put an asterisk
}
.
.
.

输出

*     
|     
*     |     
|     |     
*     |     |     
*  |     |     |     
---------------------
|     |     |  
|     |     |  
*     |     |  
|     |  
*     |  
|  
*  

基本上取arr[position]的绝对值并将其用作最终条件。

编辑: 使 astrix 在arr[position]0时出现。执行以下操作:

.
.
.
int end = arr[position] < 0 ? -arr[position] : arr[position];
if(arr[position]==0) {
mat[10][j] = '*';    // if the height is zero, put an asterisk
}
for( k = 0; k < end - 1; k++) {
.
.
.

因此,从for循环中移出if,因为如果arr[position]0,则循环不会执行。

您可以使用for( k = 0; k < abs(arr[position]) - 1; k++)

否则,如果arr[position]是负数或0当arr[position]中有负数时循环将不会执行。

需要#include <stdlib.h>

您还需要将0值的子句移动到外部for循环中,以便将它们打印到图形上。

工作样品

最新更新