How to print only values other than 0

Asked

Viewed 44 times

1

Guys, I have a question. It is possible in C to print only the different values of 0.

A Case:

  • We have the exits: 2.56000, 5.00000, 3.60000 and 27.36800

  • And I want you to print as follows: 2.56, 5, 3.6 and 27.368

But with the print running in a loop where I can only put

printf("%.2f \n");

or

printf("%f \n");

or

printf("%.1f \n");

or

printf("%.3f \n");

Can someone help me?

  • You know that floating dots are about scientific data, right? And you know that 1.0 has an implicit accuracy of 5%, while 1.00000 has accuracy in the order of 5E-6, right?

2 answers

6


You can use the conversion specifier %g to solve your problem:

#include <stdio.h>

int main(void)
{
    printf( "%g\n",  2.560 );
    printf( "%g\n",  5.000 );
    printf( "%g\n",  3.600 );
    printf( "%g\n", 27.368 );

    return 0;
}

Exit:

2.56
5
3.6
27.368
  • So simple?! Hahaha thank you very much friend :D

0

Make it easier for you to print everything

#include <stdio.h>
#include <stdlib.h>
int main(){
  float num, num1=2.56000, num2=5.00000, num3=3.60000, num4=27.36800;
  printf("Informe um numero: ");
  scanf("%f",&num;

  while(num!=0){
    printf("%.2f \n",num1);
    printf("%.0f \n",num2);
    printf("%.1f \n",num3);
    printf("%.3f \n",num4);

    printf("Inf. um valor: ");
    scanf("%f",&num);
  }
  return 0;
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.