vendredi 5 juin 2020

Finding the order of the value that is constantly multiplied by a certain number

#include <iostream>

using namespace std;

int firstTargetEXP = 100;
int multipier = 2;

// Data pattern
// 1. Level = 0 -> 100
// 2. Level = 100 -> 200
// 3. Level = 200 -> 400
// 4. Level = 400 -> 800
// 5. Level = 800 -> 1600

int GetLevelFromEXP(int EXP)
{
    int level = 1;
    if (EXP < firstTargetEXP)
        return level;

    int tmp = firstTargetEXP;
    do
    {
        EXP -= tmp;
        tmp *= multipier;
        level++;

    } while (EXP >= firstTargetEXP);

    return level;
}

int main()
{
    printf("%d\n", GetLevelFromEXP(99)); // Output is 1
    printf("%d\n", GetLevelFromEXP(101)); // Output is 2
    printf("%d\n", GetLevelFromEXP(199)); // Output is 2
    printf("%d\n", GetLevelFromEXP(200)); // Output is 3
    printf("%d\n", GetLevelFromEXP(799)); // Output is 4
    printf("%d\n", GetLevelFromEXP(800)); // Output is 5
    return 0;
}

This function works correctly but If i change multipier with 1.2 It doens't give the correct output.

#include <iostream>

using namespace std;

int firstTargetEXP = 100;
double multipier = 1.2;

// Data pattern
// 1. Level = 0 -> 100
// 2. Level = 100 -> 120
// 3. Level = 120 -> 144
// 4. Level = 144 -> 173
// 5. Level = 173 -> 207

int GetLevelFromEXP(int EXP)
{
    int level = 1;
    if (EXP < firstTargetEXP)
        return level;

    int tmp = firstTargetEXP;
    do
    {
        EXP -= tmp;
        tmp *= multipier;
        level++;

    } while (EXP >= firstTargetEXP);

    return level;
}

int main()
{
    printf("%d\n", GetLevelFromEXP(99)); // Output is 1
    printf("%d\n", GetLevelFromEXP(119)); // Output is 2
    printf("%d\n", GetLevelFromEXP(120)); // Output is 2 wrong
    printf("%d\n", GetLevelFromEXP(125)); // Output is 2 wrong
    printf("%d\n", GetLevelFromEXP(147)); // Output is 2 wrong
    printf("%d\n", GetLevelFromEXP(200)); // Output is 3 wrong
    return 0;
}

My main purpose is to find the order of the value that is constantly multiplied by a certain number so I won't have to define for every range.

This is the only algorithm I can think of, I think I'm stuck on this, I can't think of any other algorithm.

Where am I missing?

Aucun commentaire:

Enregistrer un commentaire