input in C programming language -
i want code receive user floating number store 2 digit after decimal point
for example if user input
a=123.123456789
a value equal 123.12
#include <stdio.h> int func(int x,int digit,int con,char* s) { int v; v=x/digit; v=v*digit; x-=v; if(con==1){ printf("%d %s(s) de r$ %.2f\n",(v/digit),s,(float)digit/100); return x; } printf("%d %s(s) de r$ %.2f\n",(v/digit),s,(float)digit); return x; } int main() { int x=0; float y;//if change double result true scanf("%f",&y); //y = ((int)(100.0 * y)) / 100.0; x=(int)y; y=y-x; printf("notas:\n"); char* arr="nota"; x=func(x,100,0,arr); x=func(x,50,0,arr); x=func(x,20,0,arr); x=func(x,10,0,arr); x=func(x,5,0,arr); x=func(x,2,0,arr); printf("moedas:\n"); arr="moeda"; x=func(x,1,0,arr); //mod x=y*100; x=func(x,50,1,arr); x=func(x,25,1,arr); x=func(x,10,1,arr); x=func(x,5,1,arr); x=func(x,1,1,arr); return 0; }
problem found in: https://www.urionlinejudge.com.br/judge/en/problems/view/1021
the value have 2 decimal places matter of displaying it, need print number of decimal places interested in, like
float value = 123.123456; printf("%.2f\n", value);
if want dynamicaly specify number, can use
float value = 123.123456; int decimals = 2; printf("%.*f\n", decimals, value);
if want store value string use sprintf()
or better snprintf()
.
and taking input 2 decimals not make sense anyway because output should filtered instead of input, note after ignore decimals inserted user.
also, note floating point numbers cannot store exact numbers, leave 2 decimal places doing like
float value = ((int)(100.0 * 123.1234156)) / 100.0
the actual value stored might be
123.1200000001
which has more decimal places.
one thing try is
struct realnumber { int integerpart; int decimalpart; };
and handle input read them separately, dificult.