[英]C++ Return is different if a Printf is in a function
I am experiencing a rather strange thing. 我遇到了一件很奇怪的事情。 I am currently working on a function that calculates the shape factor of a shape. 我目前正在研究一种计算形状的形状因子的函数。 The perimeter and area functions work perfectly fine however I have discovered something. 外围功能和区域功能运行正常,但是我发现了一些东西。
The code that out puts the right answer 给出正确答案的代码
double Shapefactor (char line [50][50]){
double sfactor;
double perimeter1= (Perimeter(line));
printf("peri = %f", perimeter1);
double area1=((double)Area(line));
sfactor = ((perimeter1 * perimeter1) /area1);
printf("----------------------------------------------------*Therefore the shape factor for the given shape is* %f \n", sfactor);
return (sfactor);
}
This provides me the correct output. 这为我提供了正确的输出。 However if I was to remove this line from the code 但是,如果我要从代码中删除此行
printf("peri = %f", perimeter1);
Then it gives me the wrong number. 然后给我错了号码。 Do you have any idea why this is? 你知道为什么会这样吗?
Area code 区号
int Area (char line [50][50]){
int x;
int y;
int sum;
for (x = 0; x <= 50; x++) {
for (y = 0; y <= 50; y++) {
if (line[x][y] == '1')
sum++;
}
}
return (sum);
}
Perimeter 周长
int Perimeter (char line [50][50]){
int x;
int y;
int sumup;
FILE * f_ptr;
char filename[20];
for (x = 0; x < 50; x++) {
for (y = 0; y < 50; y++) {
if (line[x][y + 1] == '0' & line[x][y] == '1')
sumup++;
else if (line[x][y] == '1' & line[x][y - 1] == '0')
sumup++;
else if (line[x + 1][y] == '0' & line[x][y] == '1')
sumup++;
else if (line[x][y] == '1' & line[x - 1][y] == '0')
sumup++;
}
}
return (sumup);
}
Thank you 谢谢
The variable sum
in Area()
(EDIT: and also sumup
in Perimeter()
, as noted by @agbinfo) is uninitialized: 可变sum
在Area()
编辑:和也sumup
在Perimeter()
如由@agbinfo说明)时不被初始化:
int Area (char line [50][50]){
//...
int sum;
for (x = 0; x <= 50; x++) {
for (y = 0; y <= 50; y++) {
if (line[x][y] == '1')
sum++;
//...
This is undefined behavior; 这是未定义的行为; this being an automatic variable, it's likely what you're reading there is garbage left on the stack by a previous function call, ie whether you invoke printf()
or not makes the difference you're seeing. 这是一个自动变量,您正在读取的内容很可能是前一个函数调用在堆栈上留下的垃圾,即您是否调用printf()
都会产生与众不同的效果。
I recommend enabling compiler warnings and linters which would usually catch these sort of errors. 我建议启用编译器警告和警告,它们通常会捕获此类错误。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.