c - 在 C 中使用矩阵绘图
问题描述
如何绘制 n 不大于 10 的函数 x+y=n 以及仅使用没有任何函数或库的矩阵的坐标系?我是初学者,希望你能帮助我。
#include<stdio.h>
int main() {
int n,i,j;
scanf("%d", &n);
char m [12][63]={" "};
for(i=0;i<12;i++){
for(j=0;j<63;j++){
m[i][j]=' ';
if(i==0 && j==1) m[i][j]='0';
if(i==11 && j==61) m[i][j]='2';
if(j==0 && i!=0 && i!=11) m[i][j]='0'+10-i;
if(j==2 && i!=11) m[i][j]='+';
if(i==11 && j%3==2) m[i][j]='0'+((j-2)/3)%10;
if(i==11 && j%3==1 && j>29 && j<59) m[i][j]='1';
if(i==10 && j%3==2) m[i][j]='+';
if(j==3*(n+i-10) && i>2 && j>2) m[i][j]='*';
}
}
for(i=0;i<12;i++){
for(j=0;j<63;j++){
printf("%c", m[i][j]);
} printf("\n");
}
}
//my code doesn't print the correct result(the coordinate system is correct except that it prints 0+ instead of 10+ on y axis and x+y=n is not correct
0+
9 +
8 +
7 +
6 +
5 +
4 +
3 +
2 +
1 +*
0 + +* + + + + + + + + + + + + + + + + + + +
0 1 2* 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
解决方案
我不知道你在这些条件下尝试了什么。检查这个
#include <stdio.h>
#include <string.h>
#define N 100
int main() {
int n;
char m[N][N];
while( scanf("%d", &n) != 1 && n > (N-1)/2 );
memset(m, ' ', N*N);
for(int i = 0; i < n-1; i++) {
m[i][0] = '*';
m[i][i] = '*';
}
for(int i = 0; i < (n-1)*2; i++) m[n-1][i] = '*';
for(int i = 0; i < n; i++) {
for(int j = 0; j < (n-1)*2; j++) printf("%c", m[i][j]);
puts("");
}
return 0;
}
该程序可以改进,它浪费了大量内存并打印了很多不必要的空格。尝试通过减少矩阵的未使用部分来改进它。这样,您还将减少不必要的打印。