Nic Bowles
Nic Bowles

Reputation: 19

Question on 0 showing up under my output in CodeRunner

I keep getting the correct output answers from the input I get on test cases for my problem on my homework but under my output in CodeRunner, it will show a 0 or crazy decimal under the correct output making the test case wrong. Any Suggestions?

double calcSimScore(string, string);

int main()
{
    calcSimScore("CATTATGCATTATATACAT", "CATCACCACCCTCCTCCTC");
}

double calcSimScore(string str1, string str2)
{
    int i;
    int count = 0;

    if (str1.length() == str2.length())
    {
        for (i = 0; i < str1.length(); i++)
        {
            string s1 = str1.substr(i, 1);
            string s2 = str2.substr(i, 1);
            if (s1 != s2)
            {
                count++;
            }
        }

        if (str1.length() - count == 0)
        {
            cout << 1 << endl;
        }
        else
        {
            float str = str1.length() - count;
            float len = str1.length();
            float simScore = str / len;
            cout << simScore << endl;
        }
    }
    else
    {
        cout << 0;
    }
}

the output I get on CodeRunner is:

0.315789 3.22526e-319

Upvotes: 0

Views: 59

Answers (1)

user10957435
user10957435

Reputation:

user4581301 is right. What you are doing by not returning a value from your non-void function is actually undefined behavior:

Flowing off the end of a function [...] results in undefined behavior in a value-returning function.

Undefined behavior, if you haven't run into it yet literally permits anything to happen, including appearing to work or printing some weird result.

Upvotes: 1

Related Questions