即使我做对了,C课的矩阵问题分数也很低?

  • 本文关键字:问题 c matrix
  • 更新时间 :
  • 英文 :


在这里学习计算机科学的大一新生遇到了这样的问题:

"假设存在一个维数为mxn的矩阵,表示m个用户在n个月内的通话值。编写一个C程序,确定电话公司为所有用户注册相同价值的月份。数据传输将完全通过参数来完成。">

这就是我所尝试的,并获得了5/10的评分。谁能告诉我什么是错误的代码或提供一个更好的解决方案?

#include<stdio.h>
#include<conio.h>
void main()
{
int a[3][3],i,j,k,n,m,vectorfound[100],p,foundmonth;
printf("Number of months: ");scanf("%d",&m);
printf("Number of customers: ");scanf("%d",&n);
for(i=0;i<m;i++)
for(j=0;j<n;j++)
{
printf("a[%d][%d]= ",i,j);scanf("%d",&a[i][j]);
}
printf("You have chosen the matrix: "); printf ("n");

for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
printf("%d ",a[i][j]); printf("n");
}

for(i=0;i<m;i++)
{
p=0; foundmonth=1; k=a[i][0];               
for(j=1;j<n;j++)
if (a[i][j]!=k) foundmonth=0;
if (foundmonth)                                     // only executes if a month has been found
{
printf("The months in which the company has recorded the same value for all of the customers are: ");
vectorfound[p]=i; // vector which saves the months with the constant value
printf("%d ",vectorfound[p]);
p++; 
} 
}

getchar();
}

main的第一个语句

int a[3][3],i,j,k,n,m,vectorfound[100],p,foundmonth;
printf("Number of months: ");scanf("%d",&m);
printf("Number of customers: ");scanf("%d",&n);
for(i=0;i<m;i++)
for(j=0;j<n;j++)
{
printf("a[%d][%d]= ",i,j);scanf("%d",&a[i][j]);
}

mn大于3时,您处于未定义的行为区域,有很强的崩溃可能性。你的a数组不够大,不能容纳任何大于3x3的东西。

另外,for-lopp中的printf语句位于scanf语句之前。无论打印的是什么,都可能是堆栈中的垃圾数据。

最新更新