0

I was trying to solve a competitive coding question which required building a series 7,77,777,..., for that I wrote a code in c++

#include<iostream>
#include<math.h>
using namespace std;
int main()
{
    int series=0;
    for(int i=0;i<6;i++)
    {
        series += (pow(10,i))*7;
    }
    return 0;
}

I was getting the required answer while dry-running but while running through MinGW compiler, the answer I got was 7,77,776,7776,77775,... does this have anything to do with bit conversion? I tried running the same code in python and got the required answer.

Botje
  • 26,269
  • 3
  • 31
  • 41
loksoni
  • 177
  • 3
  • 12
  • 6
    [std::pow](https://en.cppreference.com/w/cpp/numeric/math/pow) take a look at the function signature. It's floating point, not integer. So you are seeing rounding errors. – Ext3h Aug 04 '20 at 08:56
  • try casting `pow` to `int` like: `((int)pow(10,i))*7` – maha Aug 04 '20 at 08:57
  • I tried typecasting to int but still didn't get the correct answer `7,77,770,7770,77763,...` I'll just make my own power function and get back. – loksoni Aug 04 '20 at 09:03
  • Please provide task description. For now it looks like you do not need do any multiplication. Just print character multiple times. – Marek R Aug 04 '20 at 09:05
  • 2
    You may want to use `series *= 10; series += 7;` instead of `series += (pow(10,i))*7;`. It doesn't involve floating point calculations. – Ted Lyngmo Aug 04 '20 at 09:06

0 Answers0