0

I am new in C programming and I have problem with this small code:

int main(){
    int score = 0;

    score = score + pow(2, 1);
    printf("%d", score);
    return 0;
}

When I compile this code with -Wconversion I get this error:

error: conversion from ‘double’ to ‘int’ may change value [-Werror=float-conversion]

On this line:

score = score + pow(2, 1);

How can I fix this problem?

david
  • 65
  • 1
  • 6
  • Where are your `#include`s ? – Jabberwocky Mar 12 '22 at 11:01
  • 1
    @david Cast the result explicitly to the type int. – Vlad from Moscow Mar 12 '22 at 11:01
  • 2
    By not using a sledgehammer to crack the nut, for powers of 2. `score = score + (1 << 1) ;` Where possible, avoid the use of `pow()` when working with integers. Please see [The most efficient way to implement an integer based power function pow(int, int)](https://stackoverflow.com/questions/101439/the-most-efficient-way-to-implement-an-integer-based-power-function-powint-int). – Weather Vane Mar 12 '22 at 11:03

1 Answers1

0

You can fix the problem by not using functions which return floating point values within integer calculations. Read up on pow() to find out why that applies here.
The idea to just cast the result does not solve the problem, it just hides it.
You want a calculation of integral powers, for (and relying on) a situation in which non-integral results are not in scope.

For background see Is floating point math broken? it explains what "values may change" means.

Yunnosch
  • 26,130
  • 9
  • 42
  • 54