如何在C语言中将数字视为值1?

4
我有一个在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 的? - Rogue
仔细看 results[j] == 1; 这一行。这行代码是做什么的?你有没有收到编译器警告并且读懂了它们?请使用 -Wall 编译。 - Jabberwocky
如果results[j] == 1,则应将此数字计为1。也许我需要在这里写另一件事。 - deadman
@deadman 问问自己这个更一般的问题:语句 a == b; 做了什么? - Jabberwocky
1
hist[j] >= 10 && hist[j] < 1 永远不会成立。我想你需要用 || 或者其他东西代替 && - High Performance Mark
显示剩余2条评论
1个回答

1
以下条件存在两个问题:

 if (hist[j] >= 10 && hist[j] < 1)
 {
    results[j] == 1;
 }
  1. 比较出现错误。数值不能同时大于9并且小于1。应该使用或者
  2. 索引应该递增1,实际上是错误索引的比较==

替换:

 if (hist[j] >= 10 || hist[j] < 1)
 {
     results[1]++;
 }

但是使用双重for循环的结构比必要的复杂。可以用单个for循环来代替:

for (j = 0; j < inputValue; ++j) {
    int value = hist[j];
    if(value >= 1 && value <= 9) {
       results[value]++;
    }
    else {
       results[1]++;
    }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接