Float Returns 0
EDIT #3: So when I compile with gcc, it all works fine. It only gives me 0 if I use clang (version 3.0). I'm so confused as to why clang wouldn't work for this since it seems relatively simple.
EDIT #2: Okay, so I've confirmed thanks to everyone that the code does work, but it's probably the environment. I'm doing all this in Ubuntu on an ARM Samsung Chromebook (through chroot actually). I'm using clang 3.0 (with only -o flag) to compile everything. I'm typing everything in vim. Is it because I'm on ARM that this is happening?
I've been staring at this for two hours and can't catch my mistake. Float just seems to return 0.000000 no matter what I do. I've tried dividing by 10000.0, storing 10000 in a variable of type float, of type double as well.
I've even written a tiny program that only had a variable of type float with 1.1 stored and then a printf("%f", variable) and it printed 0.000000.
EDIT: Forgot to mention that the 1.1 was just there because I was just testing float.. I know I have to divide by 10000, haha.
What am I doing wrong?
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <stdbool.h>
bool diceRoll (int a)
{
int n = 0;
int b = 0;
while(n < 1) {
b = rand() % 12;
if(b == a || b == 6) n++;
}
if(b == 6) return false;
else return true;
}
int main (void)
{
srand( (unsigned)time(NULL));
int a, n, house, player;
float houseWinRate, playerWinRate;
house = 0;
player = 0;
float total = 1.1;
for(n = 0; n < 10000; n++) {
a = rand() % 12;
if(a == 1 || a == 2 || a == 11) {
house++;
}
else if(a == 6 || a == 10) {
player++;
}
else {
if(diceRoll(a) == true) player++;
else house++;
}
}
printf("%i, %fn", house, total);
houseWinRate = house / total;
playerWinRate = player / total;
printf("The house has %i points. That's a winrate of %f.n", house, houseWinRate);
printf("The player has %i points. That's a winrate of %f.n", player, playerWinRate);
return 0;
}
[RESOLVED] OP verified this code to be working with gcc on Chromebook.
This is not an answer, but stuff here cannot be posted to the comment.
Can you try *100
before /total
? (referring to your codepad code)
Also try the simplest test app to test only arithmetic part (also using double for houseWinRate
):
int main (void)
{
// using hardcoded value here
int house = 5492;
int player = 4508;
double houseWinRate = 0.0;
float playerWinRate = 0.0;
float total = 10000.0;
houseWinRate = ((double)house / total) * 100.0;
playerWinRate = (player * 100.0) / total;
printf("[double] The house has %i points. That's a winrate of %lf percent.n", house, houseWinRate);
printf("[mul first] The player has %i points. That's a winrate of %f percent.n", player, playerWinRate);
}
链接地址: http://www.djcxy.com/p/15990.html
上一篇: contentInset用于QLPreviewController
下一篇: 浮点返回0