-2

I think there is something wrong with my for loop?


using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System;
using BreakInfinity;
using System.Numerics;

public class Notation : MonoBehaviour { public int[] length; public string[] letter;

void Start()
{
    length = new int[11] { 7,10,13,16,19,21,24,27,30,33,36};
    letter = new string[11] { "K", "M", "B", "T", "q", "Q", "s", "S", "O", "N", "D" };
}

public BigDouble Divide(BigDouble num, int power)
{
    return num / Math.Pow(10, power);
}

public string Notate(BigDouble num)
{
    int digits = num.ToString().Length;

    if (num >= 10000)
    {
        if (digits > 36)
        {
            return "infinite";
        }
        else
        {
            for (int i = 0; i < 11; i++)
            {
                return Divide(num, digits - 2).ToString("F2") + letter[i];
            }
        }
    }
    else
    {
        return num.ToString();
    }
}

}

1 Answers1

1

Since you didn't specify what exact error is shown and where I can only guess the problem here. But I will still try to help, although quite late, but it might help someone else in the future with something similar.

I assume that the compiler complains that "not all code paths return a value" in Notate. The reason is that every single path through those if/else in that method need to end in an return statement, which is missing in the inner else part. More precisely in the for loop. Although it does contain a return statement, that one "does not count" to satisfy the condition of the else to end in an return statement. The reason for this is that a for loop also executes a conditional statement in order to run, so theoretically it could also be skipped depending on its conditional statement. "Obviously" this is not the case here as only an integer is iterated, but for the compiler it is not "that obvious". So to fix this you need to end the else in return statement that will always be hit - so outside of the for loop.

Moreover the for loop is actually quite useless as it will return on its first iteration making all other iterations useless. Also if the content of letter does not change, then you will always end up with the same string - so no need to create it every time. And while we are on the path of improving the code I strongly suggest to avoid nested if/else, because they become easily unreadable and thus hard to follow. And they are easy to "untangle" if they end up in a return statement by inverting their logic and returning immediately.

Here's my suggestion (although I'm not sure what you want to achieve with the for loop on letter which I've replaced with string.Join):

public string Notate(BigDouble num)
{
    if (num < 10000)
        return num.ToString();
int digits = num.ToString().Length;

if (digits &gt; 36)
    return &quot;infinite&quot;;

return Divide(num, digits - 2).ToString(&quot;F2&quot;) + string.Join(&quot;&quot;, letter);

}

Izzo
  • 31