简体   繁体   中英

Print values of a Matrix C++

I wrote this code that is composed of two files: main.cpp and matrice.cpp.

My problem is: the matrix does not write the values ​​in place that I indicate. I want you to write on the main diagonal all 1: A[i][i]= 1; but the result is different.

What is the error? Why, when I print out the value of the matrix, appear 6.86636e-44?

main.cpp:

#include <iostream>
#include <stdio.h>
#include "matrice.h"
#include "stampaMatrice.h"


using namespace std;
#define N 10
#define Inizio 0.00
#define Fine 1.00

float dy=(Fine-Inizio)/N;

int main()
{
    float ** A = matrice(dy, N);
    stampaMatrice(&A[0][0],N,N);

    //Clean up array
    for (int i = 0; i < N; i++)
          { delete [] A[i]; }
    delete [] A;
    A = 0;

    return 0;
}

matrice.cpp:

#include <stdlib.h>
#include <stdio.h>
#include <iostream>
using namespace std;

float** matrice(float dy, int N){

float** A=0;
A=  new float*[N];
for(int i=0; i<N; i++){
A[i]=new float[N];
}

//Assegnazione valori
for(int i=0; i<N; i++){
//A[i][i+1]=1;
//A[i][i-1]=1/dy;
A[i][i]=1;

}


return A;
}

Result:

Result

You are misreading your results. All the values on the main diagonal are 1 just as you set them. Look closely.

You didn't set the values off the main diagonal to any particular value. So there's no reason you should expect any particular values. You'll get whatever junk happens to be there.

You have to set the off-diagonal elements to zero. C++ does not perform zero-initialization if you don't explicitly say so.

BTW, float** A=0; does not set the elements of the matrix to zero . You happen to get lots of zeros as this is what probably lied at those memory addresses.

"Fixing" this is easy: just change

A[i]=new float[N];

to

A[i]=new float[N]();

Now you have all the quirks of C++ in just 20 lines of code.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM