简体   繁体   English

打印矩阵 C++ 的值

[英]Print values of a Matrix C++

I wrote this code that is composed of two files: main.cpp and matrice.cpp.我写的这段代码由两个文件组成:main.cpp 和 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;我要你在主对角线上写全 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?为什么,当我打印出矩阵的值时,会出现 6.86636e-44?

main.cpp:主.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:矩阵.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.正如您设置的那样,主对角线上的所有值都是 1。 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.如果您没有明确说明,C++不会执行零初始化。

BTW, float** A=0;顺便说一句, 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.现在,您只需 20 行代码即可掌握 C++ 的所有怪癖。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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