POW aus cmath unter GCC macht Probleme



  • Hallo zusammen,

    ich versuche grade die Potenzfunktion std::pow aus der <cmath> zu nutzen:

    #include <iostream>
    #include <cmath>
    
    
    using namespace std;
    
    
    int main()
    {
    
    
    
        float fFactor = pow((4096/10),(1/(200-1)));
    
        cout<<"Faktor: "<< fFactor <<endl;
       
        return 0;
    }
    
    

    Laut Taschenrechner müsste 1.030688516 rauskommen.
    Bei mir kommt jedoch immer nur 1 raus.

    Wo liegt mein (offensichtlicher) Fehler?

    VG


  • Mod

    Teste mal den Wert deiner Unterausdrücke (4096/10) und (1/(200-1)). Das ist nicht das, was du denkst.



  • Danke für den Tipp!
    Muss tatsächlich Ganzzahlen mit float erneut Casten.
    Dann scheint es für den Term zu gehen



  • float fFactor = pow((4096.f/10),(1.f/(200-1)));
    

    Da du von casts sprichst: nimm gleich die korrekten literale.
    0 int
    0. double
    0.f float
    0l long
    usw.



  • Im Gegensatz zu anderen Sprachen (z.B. Python oder Pascal) ist in C und C++ der Ergebnistyp des Operators / abhängig davon, welche Typen durcheinander geteilt werden, d.h. es gibt nicht // (Python) oder div (Pascal) für Integer-Division, sondern diese wird durchgeführt, wenn die Operanden auch Integer sind.

    Zitat Seite 132, Abschnitt 7.6.5.4, aus https://isocpp.org/files/papers/N4860.pdf

    The binary / operator yields the quotient, and the binary % operator yields the remainder from the division
    of the first expression by the second. If the second operand of / or % is zero the behavior is undefined. For
    integral operands the / operator yields the algebraic quotient with any fractional part discarded;75
    if the
    quotient a/b is representable in the type of the result, (a/b)*b + a%b is equal to a; otherwise, the behavior
    of both a/b and a%b is undefined.
    (...)
    75 This is often called truncation towards zero.


Anmelden zum Antworten