Francesco Bonizzi
Francesco Bonizzi

Reputation: 5302

Square root function (math.h) - C

I think that my problem is very stupid... My function doesn't return a decimal value, but an int value... How can I solve this? Thanks!

        #include <stdio.h>
        #include <stdlib.h>
        #include <math.h>

        int main()
        {
          //Dichiarazione variabili
          int nCasuale, i, MAX = 0, min = 100;
          float radice;

          //Generazione numeri casuali
          srand(time(NULL));

          for (i = 0; i < 10; ++i) //Ciclo numeri casuali
            {
              nCasuale = 1 + rand() % 100; //Casuale tra 1 e 100
              printf("Numero casuale[%d]: %d\n", i, nCasuale); //Lo stampo

              radice = sqrt(nCasuale); //Radice del numero
              printf("Radice quadrata(%d)= %2.f\n\n", nCasuale, radice); //Stampo

And so on...

I don't understand why... Thanks for help =)

Upvotes: 1

Views: 3118

Answers (1)

unwind
unwind

Reputation: 399803

You are printing the square root with the format specifier "%2.f", this tells printf() to suppress any digits after the decimal point.

You probably meant "%.2f" to get two fractional digits.

Upvotes: 11

Related Questions