我的 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] ;
}
}
}
uj5u.com熱心網友回復:
以下情況有2個問題:
if (hist[j] >= 10 && hist[j] < 1)
{
results[j] == 1;
}
- 比較被打破了。值不能同時大于 9和小于 1。它應該是OR。
- 應該是索引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] ;
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/518371.html
標籤:C
