[英]Why is the value of a variable changed when I did not assign a new value to it?
[英]Value of a variable that i did not initialize
我有這個練習,我不理解方法 float set(void)。所以,首先 A::v 被初始化為一個未知數(例如 1234),但在 A::v = v + 1.0 之后。
結果應為 A::v= 1234 + 1.0。
不是,而是 A::v=1。
#include <iostream>
using namespace std;
class A {
public:
float v;
float set(void) {
A::v = v + 1.0;
return A::v;
}
};
int main() {
A a;
cout<<a.set()<<endl;
return 0;
}
您只是沒有在 class 中初始化值。當您在堆棧上分配空間時,值是隨機垃圾。
#include <iostream>
using namespace std;
class A {
public:
float v = 1234.0; //You must initialize it with 1234 if you want result 1235
float set(void) {
/*A::v*/ v = v + 1.0;
return A::v;
}
};
int main() {
A a; //Initializing space on stack, uninitialized values are always, 0x00, 0xcd or trash from other functions.
cout<<a.set()<<endl;
return 0;
}
為什么值始終為 1 的問題的答案:好吧,事實並非如此。 這取決於 memory 中剩下的內容。您已經看到一些示例,其中未初始化的浮點值非常小,以至於將 1.0 添加到它會產生接近 1.0 的值
但事實並非總是如此。 將變量初始化為 0。
進一步閱讀:What Every Computer Scientist Should Know About Floating-Point Arithmetic
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.