Thread: pow command

  1. #1
    Registered User
    Join Date
    Dec 2008
    Posts
    8

    pow command

    I'm a really newbie to programming so sorry if this is a silly question. But why does my code produce 1 less for 5^2 and for all multiples of 5 eg 5^2=24 and 10^2=99.

    Code:
    #include <iostream>
    #include <stdio.h>
    #include <math.h>
    using namespace std;
    int main ()
    {
    int y=0, sum=0 ;
        for ( int x=1 ; x<21 ; x++){
            int y= pow(x,2);
            sum += y;
            cout << "x=" <<x<<endl;
            cout << "y=" <<y<<endl;
            cout << "sum=" <<sum<<endl;
    }
    }

  2. #2
    Registered User
    Join Date
    Dec 2005
    Location
    Colchester, Essex, United Kingdom.
    Posts
    31
    What happens when you compile and and run this code?
    Code:
    #include <iostream>
    #include <cmath>
    
    int main(){
      for(int x=1;x<21;x++){
        int y = pow(x,2);
        std::cout << y << std::endl;
      }
    }
    You should definitely be getting the square numbers from 1 to 400.
    If it wasn't for C, we'd be using BASI, PASAL and OBOL.

  3. #3
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    Quote Originally Posted by whiterebbit
    But why does my code produce 1 less for 5^2 and for all multiples of 5 eg 5^2=24 and 10^2=99.
    Such a bug could be due to floating point inaccuracy. A possible fix could be to add some small value to the result of pow() before converting back to int, e.g.,
    Code:
    int y = static_cast<int>(pow(x, 2) + 0.0001);
    Of course, you really should just use x * x instead of pow()

    By the way, you might want to indent your code properly and remove the #include <stdio.h> since you do not use it. <math.h> should also be <cmath> since the former is the C version of the C++ standard header. Oh, and I note that you actually have two variables named y: one exists directly in the scope of the main() function while the other exists in the scope of the for loop. You probably only want to keep the one that exists in the scope of the for loop.
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  4. #4
    Registered User
    Join Date
    Dec 2008
    Posts
    8

    pow command

    Have you run it on your computer it still gives 5^2=24 does it give the same answer on yours.

  5. #5
    Registered User
    Join Date
    Dec 2008
    Posts
    8
    laserlight thanks for the response. Could you please explain what
    [code]
    int y = static_cast<int>(pow(x, 2) + 0.0001);
    [/code ]
    actually does, I think I understand it but it would help so I could use it again in other programs.

    Secondly sorry I'm new could you please explain the rules for indenting code.

  6. #6
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    To paraphrase the C++ standard: the result of the expression static_cast<T>(expr) is the result of converting the expression expr to type T, except that some kinds of type conversions are not allowed, e.g., casting away const-ness.

    By the way, the expression should be:
    Code:
    int y = static_cast<int>(pow(x, 2.0) + 0.0001);
    The 2.0 is important since std::pow() is overloaded but none of the overloads match int. Therefore, you need to use 2.0 instead of 2 so that the overload for double is matched. You might not face this with the C header <math.h> since the overloads would only come into play for the C++ header <cmath>.

    Quote Originally Posted by whiterebbit
    Secondly sorry I'm new could you please explain the rules for indenting code.
    Everytime the code is nested increase the indent level by 1, and everytime it leaves the nesting decrease the indent level by 1. Be consistent with your indentation and choose a consistent brace placement policy. For example:
    Code:
    int main()
    {
        bool x = true;
        if (x)
        {
            while (x)
            {
                // ...
            }
        }
        else
        {
            // ...
        }
    }
    Last edited by laserlight; 12-11-2008 at 07:46 AM.
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  7. #7
    Registered User
    Join Date
    Dec 2008
    Posts
    8
    Thank you very much that has solved it. Could you please explain the C++ code indenting rules so I can post it correctly in forums.

  8. #8
    Registered User
    Join Date
    Dec 2008
    Posts
    8
    cheers

  9. #9
    Kernel hacker
    Join Date
    Jul 2007
    Location
    Farncombe, Surrey, England
    Posts
    15,677
    Note however that using pow(x, 2.0) to square a integer number is like using a lorry to do your weekly shopping - using x * x will be MUCH simpler for the computer to do the calculation, with the added advantage of it being precise.

    --
    Mats
    Compilers can produce warnings - make the compiler programmers happy: Use them!
    Please don't PM me for help - and no, I don't do help over instant messengers.

  10. #10
    Frequently Quite Prolix dwks's Avatar
    Join Date
    Apr 2005
    Location
    Canada
    Posts
    8,057
    Indentation article on cpwiki: cpwiki.sf.net/Indentation

    (I must say that cpwiki is more alive than I thought it would be after all this time! )
    dwk

    Seek and ye shall find. quaere et invenies.

    "Simplicity does not precede complexity, but follows it." -- Alan Perlis
    "Testing can only prove the presence of bugs, not their absence." -- Edsger Dijkstra
    "The only real mistake is the one from which we learn nothing." -- John Powell


    Other boards: DaniWeb, TPS
    Unofficial Wiki FAQ: cpwiki.sf.net

    My website: http://dwks.theprogrammingsite.com/
    Projects: codeform, xuni, atlantis, nort, etc.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 26
    Last Post: 07-05-2010, 10:43 AM
  2. problem with "touch" command in c program
    By Moony in forum C Programming
    Replies: 10
    Last Post: 08-01-2006, 09:56 AM
  3. Batch file programming
    By year2038bug in forum Tech Board
    Replies: 10
    Last Post: 09-05-2005, 03:30 PM
  4. Ping problem
    By bladerunner627 in forum C++ Programming
    Replies: 12
    Last Post: 02-02-2005, 12:54 PM
  5. exe files in -c- language
    By enjoy in forum C Programming
    Replies: 6
    Last Post: 05-18-2004, 04:36 PM