浮点矩阵作为参数传递给函数会产生垃圾值。

huangapple go评论66阅读模式
英文:

Float matrix passed as a parameter to a function gives garbage values

问题

我想将一个 float 矩阵从主函数传递给另一个函数,代码如下所示:

#include <stdio.h>

// 在传递二维数组之前必须传递 n
void print(int m, int n, float arr[][n])
{
    int i, j;
    for (i = 0; i < m; i++)
      for (j = 0; j < n; j++)
        printf("%d ", arr[i][j]);
}

int main()
{
    float arr[][3] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
    int m = 3, n = 3;
    print(m, n, arr);
}

这会输出:3 -1742458874 -1742458874 -1742458874 -1742458874 -1742458874 -1742458874 -1742458874 -1742458874

我尝试用 int 替换 float 作为数组的类型,这样做完全正常。我期望它与 float 一样工作,输出 "1 2 3 4 5 6 7 8 9",但实际上它输出垃圾值。

英文:

I want to pass a float matrix to another function from the main function, the code being as follows:

#include &lt;stdio.h&gt;
 
// n must be passed before the 2D array
void print(int m, int n, float arr[][n])
{
    int i, j;
    for (i = 0; i &lt; m; i++)
      for (j = 0; j &lt; n; j++)
        printf(&quot;%d &quot;, arr[i][j]);
}
 
int main()
{
    float arr[][3] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
    int m = 3, n = 3;
    print(m, n, arr);
}

This gives the output: 3 -1742458874 -1742458874 -1742458874 -1742458874 -1742458874 -1742458874 -1742458874 -1742458874

I tried this by replacing float with int for the type of the array and it works perfectly fine. I expected it would work the same way with float, outputting "1 2 3 4 5 6 7 8 9" but instead it outputs garbage values.

答案1

得分: 1

%d 不适用于 float。使用 %f 应该解决问题,并且你应该看到预期的结果。如果你只想打印浮点数的“整数”部分,你也可以指定精度:

printf("%.0f ", arr[i][j]);
英文:

%d is the wrong format for floats. Using %f should solve the issue, and you should see the expected results. If you want to print only the "whole" part of the float, you can specify the precision too:

printf(&quot;%.0f &quot;, arr[i][j]);

huangapple
  • 本文由 发表于 2023年5月21日 20:16:30
  • 转载请务必保留本文链接:https://go.coder-hub.com/76299864.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定