有誰知道我如何通過 c 中的函式對 {5, 0, 2, 6} 這樣的陣列進行處理,如下圖所示?

我是 C 的新手,所以我真的可以在這里使用一些幫助:)
這就是我現在所擁有的:
#include <stdio.h>
int Diagram(int i, int x, int y, int v[])
{
printf("y \n");
for(i = 0; i <= y; i ){
printf(" |\n");
}
printf(" ");
for(i = 0; i <= x; i ){
printf(" ---");
}
printf(" x");
return 0;
}
int main()
{
int i;
int y = 10;
int x = 5;
int v[4] = {5, 0, 2, 6};
Diagram(i, 5, 10, v);
return 0;
}
uj5u.com熱心網友回復:
正如@Eugene 在評論中所說,解決這個問題的最簡單方法是創建一個臨時陣列,“繪制”到該陣列中,然后將其列印到螢屏上。例如:
void Diagram(int w, int h, int v[]) {
char a[h][w 1];
// initialize with blank lines
for(int y = 0; y < h; y) {
memset(a[y], ' ', w);
a[y][w] = 0;
}
// draw the bars
for(int x = 0; x < w; x)
for(int y = 0; y < v[x] && y < h; y)
a[y][x] = '|';
// print the array onto the screen (in reverse order)
for(int y = h; y --> 0; )
puts(a[y]);
}
int main() {
int v[4] = {5, 0, 2, 6};
Diagram(4, 10, v);
}
這列印:
|
| |
| |
| |
| ||
| ||
我將把它留給您作為繪制軸和增加條形間距的練習。您需要為此增加陣列的大小(注意數學)。
uj5u.com熱心網友回復:
我建議將引數Diagram稍微更改為:
#include <stdio.h>
void Diagram(int graph_height, int v[], size_t cols) {
// graph_height the height you want the graph to be
// v[] the values
// cols number of columns in v
}
你會這樣稱呼它:
int main() {
int graph_height = 10;
int v[] = {8, 5, 0, 2, 6};
Diagram(graph_height, v, sizeof v / sizeof *v);
}
現在,里面Diagram:
- 首先回圈遍歷中的所有值
v[]并找到最大值。這將在稍后用于縮放圖形。 - 讓
h回圈從graph_height到1(包括)。- 讓
col回圈從0到cols - 1(包括)- 被
graph_height * v[col] / max >= h然后列印!,否則列印。 - 列印三個空格
- 被
- 列印換行符
- 讓
- 通過列印
---線完成。
仔細觀察graph_height * v[col] / max >= h:
- 在
graph_height * v[col] / max結果將是graph_height時v[col] == max。較小的值將相應地縮放。如果一個值是,max / 2它將擴展為graph_height / 2. 如果結果是>= h在!應被列印,否則。
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/383767.html
