英文:
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 <stdio.h>
// n must be passed before the 2D array
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);
}
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 float
s. 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("%.0f ", arr[i][j]);
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论