Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
220 views
in Technique[技术] by (71.8m points)

Low grade on matrix problem in C even if I did it right?

Freshman studying computer science here, had this problem:

"Assume there is a matrix of dimensions mxn, representing the value of telephone calls of m subscribers in a period of n months. Write a C program which determines the months in which the telephone company registered the same value for all subscribers. The data transfer will be done exclusively through parameters."

This is what I tried and got graded a 5/10 on it. Could anyone tell me what's wrong with the code or provide a better solution?

#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 ("
");
    
    for(i=0;i<m;i++)
    {
        for(j=0;j<n;j++)
        printf("%d ",a[i][j]); printf("
");
    }

    
    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();
}
question from:https://stackoverflow.com/questions/65851036/low-grade-on-matrix-problem-in-c-even-if-i-did-it-right

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

First statements in 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]);
    }

The moment m or n is greater than 3, you are in undefined behavior territory with a strong likelihood of crashing. Your a array isn't big enough to hold anything bigger than a 3x3.

Also, your printf statement inside the for-lopp is preceding the scanf statement. Whatever gets printed is likely garbage data off the stack.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...