浮点异常CS50可读性分配

我遇到了一些有关浮点异常错误的问题,因为以前我分别打印变量时无法确定到底出了什么问题。下面是我到目前为止编写的代码。我不确定是什么原因引起的错误,因为我很确定我没有被零除。

#include <stdio.h> 
#include <cs50.h> 
#include <ctype.h> 
#include <string.h>
#include <math.h>

int main(void)
{
    //promt user for text 
    string n = get_string("Text: ");
    int sumletters = 0; 
    int sumdots = 0;
    int sumspaces = 1;

    for (int i = 0; i < strlen (n); i++ )
    {
        if (n[i] >= 'A' && n[i] <= 'z')
        {
           sumletters = sumletters + 1; 
        }

        if (n[i] == ' ')
        {
            sumspaces = sumspaces + 1;
        }

        if (n[i] == '.' || n[i] == '?' || n[i] == '!' )
        {
            sumdots = sumdots + 1;   
        }

        float L = sumletters / (sumspaces / 100); 
        float S = sumdots / (sumspaces / 100); 
        int index = round ((0.0588 * L) - (0.296 * S) - 15.8); 

        if (index < 1)
        {
            printf ("Before grade 1\n");
        }
        {
            printf ("Grade 16+\n");
        }
        else 
        {
            printf ("Grade %i", index);
        }
    }
printf ("\n");
}
评论
  • iullam
    iullam 回复

    这是有问题的部分:

    sumletters / (sumspaces / 100)
    

    sumspaces / 100 uses integer division so it will almost always be 0. You can refactor your code to use floating point division by simply distributing the division:

    sumletters / sumspaces * 100