Jackson
Jackson

Reputation: 49

Weird C behaviour

Sorry for the ambiguous title, I don't really know what to call this issue. I'm working on an assignment for a class and I'm getting the strangest error when I try to print out a certain float variable. The program is quite long so I'll just include some snippets:

float zero,t,t1,t2,t3,t4,t5,t6,t7 = 0.0;
float pzero, pt, pt1, pt2, pt3, pt4, pt5, pt6, pt7 = 0.0;

The top line variables are total, which are divided by the number of simulations of the program, then dividing the total by the number of simulations I get the probability (last line of variables). When I run my code like this, the output is:

enter image description here

Since t6 is initialized, the only thing that occurs is it gets bigger, then divided by the simulations, and that value is 100. Just to be sure it wasn't me accidentally changing it I printed t6 out after initializing it and it had a similar value, a very low negative number. Even though it was just initialized to 0. I thought that was weird, but even stranger is when I declare my variables like this:

float zero,t,t1,t2,t3,t4,t5,t7 = 0.0;
float t6 = 0.0;
float pzero, pt, pt1, pt2, pt3, pt4, pt5, pt6, pt7 = 0.0;

The program works absolutely fine, giving me a normal probability. I'm so confused, and I was wondering if anyone knows what is going on here? I can post the full code if necessary but it seems like it's an issue with me declaring it somehow?

Upvotes: 0

Views: 64

Answers (2)

Minh-Long Luu
Minh-Long Luu

Reputation: 2731

If you want to declare multiple variables with the same value, you have to specify each value t1 = 0, t2 = 0, t3 = 0

Upvotes: 2

dbush
dbush

Reputation: 223689

This:

float zero,t,t1,t2,t3,t4,t5,t6,t7 = 0.0;

Only initializes t7 to 0 and leaves the rest uninitialized. You need to initialize each variable explicitly:

float zero = 0, t = 0, t1 = 0, t2 = 0, t3 = 0, t4 = 0, t5 = 0, t6 = 0, t7 = 0.0;

Upvotes: 4

Related Questions