我有一个在C程序中的问题。我需要编写数字的直方图。如果输入的数字不在区间[1,9]内,则将其视为值1。我不明白为什么它不起作用。
正确的输出:
#include <stdio.h>
#include <stdlib.h>
void printHistogram_vertical(int *hist, int n);
int main()
{
int i, j;
int inputValue;
scanf("%d", &inputValue);
int hist[inputValue];
for (i = 0; i < inputValue; ++i)
{
scanf("%d", &hist[i]);
}
int results[10] = {0};
for (i = 0; i < 10; ++i)
{
for (j = 0; j < inputValue; ++j)
{
if (hist[j] >= 10 && hist[j] < 1)
{
results[j] == 1;
}
if (hist[j] == i)
{
results[i]++;
}
}
}
return 0;
}
void printHistogram_vertical(int *hist, int n)
{
int i, j;
for (i = 1; i < n; i++)
{
printf(" %d ", i);
for (j = 0; j < hist[i]; ++j)
{
printf("#");
}
printf("\n");
}
}
输入:
9
3 3 2 3 7 1 1 4 10
我的输出:
1 ##
2 #
3 ###
4 #
5
6
7 #
8
9
正确的输出:
1 ###
2 #
3 ###
4 #
5
6
7 #
8
9
如果数字大于10且小于1,则应将此数字视为1。我编写了以下函数:
for (i = 0; i < 10; ++i)
{
for (j = 0; j < inputValue; ++j)
{
if (hist[j] >= 10 && hist[j] < 1)
{
results[j] == 1;
}
if (hist[j] == i)
{
results[i]++;
}
}
}
inputValue
在不在[1,9]
的范围内时等于1
的? - Rogueresults[j] == 1;
这一行。这行代码是做什么的?你有没有收到编译器警告并且读懂了它们?请使用-Wall
编译。 - Jabberwockyresults[j] == 1
,则应将此数字计为1。也许我需要在这里写另一件事。 - deadmana == b;
做了什么? - Jabberwockyhist[j] >= 10 && hist[j] < 1
永远不会成立。我想你需要用||
或者其他东西代替&&
。 - High Performance Mark