[英]Drawing matrix with characters in C
我的任務是用星號繪制矩陣,但問題是用戶輸入點數和它們的坐標,星號只能繪制在它們的 position 中。矩陣的總大小為 20x20。 並且坐標在 [0,19] 范圍內。 我只是不知道如何保存輸入的數字。 我是初學者,希望對你有所幫助。
#include <stdio.h>
int main()
{
int n, i, j, a, b;
char m[20][20] = {{0}}, x = '*';
printf("Enter the number of points: ");
scanf("%d", &n);
for (i = 0; i < n; i++)
{
printf("Enter the point %d", i + 1);
scanf("%d %d", &a, &b);
m[a][b] = x;
}
for (i = 0; i < 20; i++)
{
for (j = 0; j < 20; j++)
{
if (m[a][b])
printf("%c", m[a][b]);
else
printf(" ");
}
printf("\n");
}
}
你應該
m
。i
和j
而不是a
和b
來決定要打印的字符。固定代碼:
#include <stdio.h>
int main() {
int n,i,j,a,b;
char m[20][20]={{0}},x='*'; /* add ={{0}} to initialize the array */
printf("Enter the number of points: ");
scanf("%d", &n);
for(i=0;i<n;i++){
printf("Enter the point %d",i+1);
scanf("%d %d",&a,&b);
m[a][b]=x;
}
for(i=0;i<20;i++){
for(j=0;j<20;j++){
if (m[i][j])
printf("%c", m[i][j]);
else printf(" ");
}
printf("\n");
}
}
當你聲明一個變量(或變量數組)時,你必須將它初始化為一個特定的值。 否則,保存在 memory 單元格中的值與分配前相同(通常是與 ascii 字符不對應的無意義數字)。 您可以手動初始化它們或使用memset
或bzero
等庫函數。
手動初始化數組:
for(i = 0; i < 20; i++)
for(j = 0; j < 20; j++)
m[i][j] = 0;
使用 memset 初始化:
memset(&m, 0, sizeof(char[20][20]));
使用 memset 的固定代碼:
#include <stdio.h>
#include <string.h>
int main()
{
int n, i, j, a, b;
char m[20][20], x = '*';
memset(&m, 0, sizeof(char[20][20]));
printf("Enter the number of points: \n");
scanf("%d", &n);
for (i = 0; i < n; i++)
{
printf("Enter the point %d\n", i + 1);
scanf("%d %d", &a, &b);
m[a][b] = x;
}
for (i = 0; i < 20; i++)
{
for (j = 0; j < 20; j++)
{
if (m[i][j])
printf("%c", m[i][j]);
else
printf(" ");
}
printf("\n");
}
}
使用 for 循環的固定代碼:
#include <stdio.h>
#include <string.h>
int main()
{
int n, i, j, a, b;
char m[20][20], x = '*';
for (i = 0; i < 20; i++)
for (j = 0; j < 20; j++)
m[i][j] = 0;
printf("Enter the number of points: \n");
scanf("%d", &n);
for (i = 0; i < n; i++)
{
printf("Enter the point %d\n", i + 1);
scanf("%d %d", &a, &b);
m[a][b] = x;
}
for (i = 0; i < 20; i++)
{
for (j = 0; j < 20; j++)
{
if (m[i][j])
printf("%c", m[i][j]);
else
printf(" ");
}
printf("\n");
}
}
Output:
****
* *
* *
* *
* *
****
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.