程序不返回float并根据使用的编译器给出不同的结果?

时间:2018-04-01 17:33:30

标签: c loops codeblocks

#include <stdio.h>
#include <stdlib.h>
#include<time.h>

void averageGuess(int);
int main()
{
    int i, userInput, compGuess, totalGuess, loopGuess = 0;
    srand(time(NULL));

    printf("Please enter a number between 0 and 99: \n");
    scanf("%d", &userInput);

    for(i = 0; i < 50; i++)
    {
        loopGuess = 0;
        do
        {
            compGuess = (rand() % 100);
            loopGuess++;
        } while(compGuess != userInput);

        totalGuess += loopGuess;
    }
    averageGuess(totalGuess);
    return 0;
}//end main

void averageGuess(int totalGuess)
{
    float average;
    average = totalGuess / 50;
    printf("The program took an average of %lf random number generations to match the target number over the 50 experiments.", average);
}//end function

目标是让程序打印出浮动,但我得到的只是整数。我在Codeblocks和在线C编译器中编译了它,但后者给了我负数,而Codeblocks 没有返回浮点数

无法判断我的代码或编译器是否存在问题。

3 个答案:

答案 0 :(得分:0)

这是代码的问题:

    average = totalGuess / 50;

&#39; /&#39;运算符看到它必须除以两个整数,因此返回一个整数。如果您需要结果为浮点数,请使用50.0而不是50

答案 1 :(得分:0)

  

我在Codeblocks和在线C编译器中编译了它,但后者给了我负数

这一行:

int i, userInput, compGuess, totalGuess, loopGuess = 0;

将所有变量设置为0,仅loopGuess。所以totalGuess没有被初始化,这解释了 不同编译器之间的行为差​​异(以及错误的结果,totalGuess的初始值是随机的,可以是负的)。修正:

int i, userInput, compGuess, totalGuess = 0, loopGuess = 0;
  

目标是让程序打印出一个浮点数,但我得到的只是整数

然后使用浮点除法,而不是整数除法

float average;
average = totalGuess / 50.0;

gcc没有警告未初始化的变量(糟糕!)但是clang确实(甚至建议正确的修复,哇!):

S:\>gcc -Wall -Wextra test.c
(no warnings!!)
S:\>clang -Wall -Wextra test.c

test.c:23:9: warning: variable 'totalGuess' is uninitialized when used here
      [-Wuninitialized]
        totalGuess += loopGuess;
        ^~~~~~~~~~
test.c:8:44: note: initialize the variable 'totalGuess' to silence this warning
    int i, userInput, compGuess, totalGuess, loopGuess = 0;
                                           ^
                                            = 0

答案 2 :(得分:0)

代码有两个问题:

a)totalGuess除以整数,因此结果四舍五入为int

average = totalGuess / 50;

b)负数来自于这样的事实 totalGuess变量未初始化,因此它可以是任何数字(如开头的大负数)。

更正程序:

#include <stdio.h>
#include <stdlib.h>
#include<time.h>

void averageGuess(int totalGuess)
{
    float average;
    average =  totalGuess / 50.0;
    printf("The program took an average of %.2f random number generations to match the target number over the 50 experiments.", average);
}

int main()
{
    int i, userInput, compGuess;
    int totalGuess = 0;
    double loopGuess = 0;

    srand(time(NULL));

    printf("Please enter a number between 0 and 99: \n");
    scanf("%d", &userInput);

    for(i = 0; i < 50; i++)
    {
        loopGuess = 0;
        do
        {
            compGuess = (rand() % 100);
            loopGuess++;

        } while(compGuess != userInput);

        totalGuess += loopGuess;
    }

    averageGuess(totalGuess);
    return 0;
}//end main