#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#define N 10
#define TEMPSIZE 1024
int DiagSum(int **p, int sizearray) {
int sum=0;
for (int i = 0; i < sizearray; i++) {
for (int j = 0; j < sizearray; j++) {
if (j == i) {
sum = sum + p[i][j];
}
}
}
return sum;
}
int SizeArray(int **p) {
int i;
for (i = 0; i < TEMPSIZE; i++) {
if (p[i] == ' ' || p[i]=='\t')
i++;
}
return p[i];
}
void main() {
int **p;
int input;
int sizear=0;
int i, j, counter = 0;
p = (int**)malloc(N * sizeof(int*));
for (j = 0; j < N; j++)
p[j] = (int*)malloc(N * sizeof(int));
while ((input = getchar()) != EOF || input != '\n') {
if (input == ' ' || input == '\t')
continue;
input = input - '0';
sizear = SizeArray(p);
for (i = 0; i < sizear; i++)
{
for (j = 0; j < sizear; j++)
{
p[i][j] = input - '0';
counter++;
}
}
if (counter > sizear*sizear) {
printf("you've entered too many numbers \n");
}
else if (counter < sizear*sizear) {
printf("you've entered not enough numbers \n");
}
for (i = 0; i < sizear; i++)
{
for (j = 0; j < sizear; j++)
{
printf("%c ", p[i][j]);
}
}
}
完全陷入困境。我的作业要求我从用户那里获得输入,只有一行。它将由矩阵的大小(n * n)组成,它将是该行中的第一个数字,以及它中的数字。例如:3 1 2 3 4 5 6 7 8 9. 3(第一个数字) - 列和列,后面的数字将是矩阵内的数字。第一个错误,最重要的是无法提取第一个数字,即数组大小,第二个可能是输入到矩阵中的错误。我该如何解决?
答案 0 :(得分:-1)
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#define TEMPSIZE 1024
int DiagSum(int **p, int sizearray) {
int sum=0;
for (int i = 0; i < sizearray; i++) {
for (int j = 0; j < sizearray; j++) {
if (j == i) {
sum = sum + p[i][j];
}
}
}
return sum;
}
void main() {
int **p;
char input[TEMPSIZE] = {0};
int sizear=0;
int i, j, counter = 0;
//get input string(size no more than 1024)
fgets(input, TEMPSIZE, stdin);
//get array size
char* str = strstr(input, " ");
if(str == 0)
return;
str[0] = 0;
str++;
sizear = atoi(input);
if(sizear <= 0)
return;
//create array
p = (int**)calloc(sizear, sizeof(int*));
for (j = 0; j < sizear; j++)
{
p[j] = (int*)calloc(sizear, sizeof(int));
}
//fill array with input
for (i = 0; i < sizear; i++)
{
for (j = 0; j < sizear; j++)
{
char* temp = strstr(str, " ");
if(temp == 0)
{
p[i][j] = atoi(str);
counter++;
goto end;
}
temp[0] = 0;
p[i][j] = atoi(str);
str = temp + 1;
counter++;
}
}
end:
if (counter > sizear*sizear) {
printf("you've entered too many numbers \n");
}
else if (counter < sizear*sizear) {
printf("you've entered not enough numbers \n");
}
for (i = 0; i < sizear; i++)
{
for (j = 0; j < sizear; j++)
{
printf("%d ", p[i][j]);
}
}
//free memory
for (j = 0; j < sizear; j++)
{
free(p[j]);
}
free(p);
}
我认为上面的代码可以帮到你!