简体   繁体   中英

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:

在此处输入图片说明

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?

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;

如果要声明多个具有相同值的变量,则必须指定每个值t1 = 0, t2 = 0, t3 = 0

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM