I have a double value which is getting updated in a loop, the increment is about 0.0001
, when I am trying to print it with cout, nothing is being printed. Whereas when I use printf("%lf", value)
, it gets printed easily. Why am I getting such behaviour ?
For eg.
I access the variable using a class object called var
, as I have stored all variables in a header file, under the class var
.
Like
variables.h
class varibles {
public:
double t;
// other variables too
};
This code below produces the right output for every updated value of var.t
For eg.
0.00001 secs
0.00002 secs
0.00003 secs
Heap.cpp
#include <bits/stdc++.h>
#include "variables.h"
#include "Heap.h"
#include "Move.h"
void Heap::Heaps(variable &var) { // var is passed from main code
for (condition) {
// code
var.t = var.t + var.dt; // t gets updated only here
printf("%lf secs \n", var.t);
// code
}
}
Whereas on using the code below it does not print anything, neither the value nor secs
.
Heap.cpp
#include <bits/stdc++.h>
#include "variables.h"
#include "Heap.h"
#include "Move.h"
void Heap::Heaps(variable &var) {
//code
for (condition) {
//code
var.t = var.t + var.dt; // t gets updated only here
cout << var.t << "secs" << endl; // this line is causing problems
//code
}
}
Here is the contents of Heap.h which contains the function declaration:
#ifndef HEAP_H
#define HEAP_H
#include <stdio.h>
#include "variables.h"
class Heap {
public:
void Heaps(variables &var);
};
#endif
and main
is defined in main.cpp:
#include <bits/stdc++.h>
#include "variables.h"
#include "Heap.h"
int main() {
variables var;
Heap heap;
var.t = 0;
// other code
while (var.t < var.tfinal)
heap.Heaps(var);
}
//code
}