Yasir Dharala Yasir Dharala - 3 years ago 60
C++ Question

Why do I keep getting the same value of a variable for each iteration? c++

i am new to c++ and I keep getting the same value for variable 'w'..

#include <iostream>
#include <string>

#define NOEXE 10
#define winit 0.9
#define wfinal 0.2

int main()
for (int nExeNo = 0; nExeNo<NOEXE; nExeNo++)
double w;

w = (((NOEXE - nExeNo)/NOEXE)*((NOEXE - nExeNo)/NOEXE))*(winit - wfinal) + wfinal;
std::cout << w << "\n";

and the output is

0.2 .......

Answer Source

(NOEXE - nExeNo)/NOEXE is done entirely in integer arithmetic. Since nExeNo < NOEXE the entire previous expression is always zero.

Thus you are left only with the final term wfinal.

To force floating point arithmetic, at least one operand must be of a floating point type (in your case a double). So to clean up, and get rid of the nasty macros, define your constants as follows:

constexpr int    NOEXE   = 10; // use const instead of constexpr for C++03
constexpr double NOEXE_D = NOEXE;
constexpr double winit   = 0.9;
constexpr double wfinal  = 0.2;

And use NOEXE_D in the calculation instead. I.e. (NOEXE_D - nExeNo)/NOEXE_D).

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download