input in C programming language - c

I want code receive from user a floating number but store only two digit after decimal point
for example if user input
a=123.123456789
a value will 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 to double the result will be 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 will found in:
https://www.urionlinejudge.com.br/judge/en/problems/view/1021

If you just want to round off to two decimal points you could try something like:
a = ((int) (a*100))/100.0;

The value have only 2 decimal places is a matter of displaying it, so you just need to print the number of decimal places you are interested in, like
float value = 123.123456;
printf("%.2f\n", value);
if you want to dynamicaly specify that number, you can use
float value = 123.123456;
int decimals = 2;
printf("%.*f\n", decimals, value);
If you want to store the value as a string then use sprintf() or better snprintf().
And taking the input with only two decimals does not make sense anyway because the output is what should be filtered instead of the input, note that after all you will ignore the extra decimals inserted by the user.
Also, note that floating point numbers cannot store exact numbers, so even i you leave only two decimal places by doing something like
float value = ((int)(100.0 * 123.1234156)) / 100.0
the actual value that is stored might be
123.1200000001
which has more decimal places.
One thing that you could try is
struct RealNumber
{
int integerPart;
int decimalPart;
};
and then handle the input to read them separately, which will be really dificult.

Related

printing floating point numbers using scientific notation depending on size

I'm storing the result of a calculation inside a long double variable that I need to print out. I need a way to discriminate between large numbers and small numbers. For example If I want to print tan(pi/4) it should be 1, the same for the result of a multiplication like '5*3' I want to be 15 without trailing zeros. On the other hand, I want to represent small numbers like the elementary charge 1.602176634e-19 using the scientific notation. This is what I tried
void print(long double number) {
long double i;
long double tmp = ceil(number);
if (fabs(number-tmp) < 0.00000001)
number = tmp;
long double r = modfl(number, &i);
if (fabs(r) <.0000000000000001 && fabs(r) <.00001)
printf("%.Lf ", i);
else if (fabs(r) <.00001)
printf("%.Lf ", i);
else printf("%.19Lf ", number);
}
If I try to print the mass of a proton 1.6726219236951e-27 with this code I get 0, the rest of the quantities I mentioned before are displayed correctly.

While loop ignores a boolean expression which compares two floating point variables

Edit:I solved the issue by first multiplying the float value by 100, then rounding it with roundf() function, then casting it to an integer to be stored in an integer variable. I did the remaining operations with integer values from there on and everything worked. Even though the solution offered by #JacobBoertjes actually worked, my assignment requiered me to use get_float() from the cs50.h library, so I didn't implement it. Here's the final code:
// Get user input as a positive float value
float f_change;
do {
printf("Change owed: ");
f_change = get_float();
} while(f_change < 0);
// Round & cast
int int_change = (int) roundf(f_change * 100);
My program accepts an amount of money, say $4.20, and figures out the least amount of coins with which it can represent this value. For example, desired output from the program with $4.20 as an input would be: 16 quarters ($4.00), 2 dimes ($0.20).My program successfully calculates the number of quarters, but fails to do so while working on dimes. The cause of this failure is the second for loop in the code. 0.10 >= 0.10 does not evaluate to true, so the last iteration of the loop never happens. What am I doing wrong? Here is the code. I provided test print statements with their outputs written as comments.
#include <stdio.h>
#include <cs50.h>
int main(void) {
// Fake user input
float owed_coin = 4.2f;
// Initialize coin variables
int coin_count = 0;
float quarters = 0.25f,
dimes = 0.10f;
// Calculate quarters
while(owed_coin >= quarters) {
owed_coin -= quarters;
coin_count += 1;
}
printf("owed_coin: %.2f\ncoin_count: %d\n\n", owed_coin, coin_count);
// Prints owed_coin: 0.20
// coin_count: 16
// Calculate dimes
while(owed_coin >= dimes) {
owed_coin -= dimes;
coin_count += 1;
}
printf("owed_coin: %.2f\ncoin_count: %d\n\n", owed_coin, coin_count);
// Prints owed_coin: 0.10
// coin_count: 17
}
Floating point comparison is generally a bad idea because floats often become non-exact and thus will not be exactly equal. As #bruceg mentioned, a good solution is to keep your monetary values in terms of cents, so that you avoid using a float.
You could replace float owed_coin = 4.2f; with int owed_coin = 420;
In terms of gathering user input into this number, here is my suggestion using scanf
int n1, n2;
printf("Please enter amount:");
scanf("%d.%2d", &n1, &n2);
owed_coin = n1*100 + n2;
Another solution allows you you keep your variables as floats, and just compare for a very small difference between the two. It can be found here: What's wrong with using == to compare floats in Java?
It uses the Java Math library, but a similar solution could look something like this in C:
while((owed_coin - dimes) >= -0.001) {
owed_coin -= dimes;
coin_count += 1;
}
If you want to learn more about why floating point numbers suffer small innacuracies then check this out: https://en.wikipedia.org/wiki/Floating-point_arithmetic#Accuracy_problems

How to take in a number and divide it into three parts positive or negative, whole number and fractions

In a school assignment we where supposed to write a program that takes in a number and divide it in three parts:
1. Check if the number is positive or negative
2. whole number (magnitude)
3. fractional parts
The requirement is that there should be a own function called separate that has input and output parameter.
For example: if you type in 23.639, the program should sort of out and print out:
Sign: +
Whole number magnitude: 23
Fractional parts: 0.639
QUESTIONS:
1.The function for sorting out whether the number is positive or negative brings forth the wrong answer when typing in a negative number. It also posts wrong character. I have tried different data types, like int, char and float, but none seem to work. Any tip on how to solve this are greatly appreciated, cause I think I'm blinded by my own errors...
2.The function separating decimals from whole numbers (fractions) won't subtract the whole number away from the decimals, so I am stuck with whole number. Can anyone spot my error here?
* UPDATE *
I managed to solve the questions at hand, and did the terrible n00b error of editing the code I first posted in this question.
I have now edited the code once more to hold the original errors as best as I can remember. The right code is posted as an answer below.
Sorry for the rookie error.
/*
Author: Thorbjørn Elvestad
Student ID: *****
E-mail: drommevandrer#gmail.com
This program take in number typed in by the user, and then divide it into three parts.
SIGN: '+' or '-'
Whole number: Show number as a whole number
Fraction: Show fractions
The program uses function to sort out the number, and print out the result*/
/* Declaring libraries */
#include <stdio.h>
#include <stdlib.h>
/* Declaring functions */
double sorting_sign(char x);
double sorting_whole(double x);
double sorting_fract(double x, int y);
/* Calling main function */
int main()
{
double num, fractures; /* declaring variables */
int sign_sorted, part;
double whole_sorted;
printf("LET ME TELL YOU SOME INTERESTING STUF ABOUT YOUR NUMBER!\n\n");
printf("Enter your number: ");
scanf("%d", &num);
sign_sorted = sorting_sign(num); /* Calling the function that sorts out if this number is '+' or '-' */
whole_sorted = sorting_whole(num); /* Calling the function separating whole number from decimals */
fractures = sorting_fract(num, num); /* Calling the function removing the whole number from the fractures */
printf("Sign: %c\nWhole: %0.lf\nFraction: %f", sign_sorted, whole_sorted, fractures);
return 0;
}
/* Function for sorting of if number is '+' or '-' */
double sorting_sign(char x)
{
int sign;
/* true if number is less than 0 */
if(x < 0.0){sign = '-';}
/* true if number is greater than 0 */
else if(x > 0.0){sign = '+';}
return (sign);
}
/* Function for sorting out the whole number */
double sorting_whole (double x)
{
int whole;
whole = x;
return (whole);
}
/* Function for sorting out the fractions */
double sorting_fract(double x)
{
int whole;
double fract;
whole = y;
fract = x - whole;
return (fract, whole);
}
You've declared your sorting_sign function to return a double, when you're returning an int set to the value of a char... sort your types out.
SOLVED!
For future reference I hereby post the code for the fully working program:
/*
Author: Thorbjørn Elvestad
Student ID: *****
E-mail: drommevandrer#gmail.com
This program take in number typed in by the user, and then divide it into three parts.
SIGN: '+' or '-'
Whole number: Show number as a whole number
Fraction: Show fractions
The program uses function to sort out the number, and print out the result*/
/* Declaring libraries */
#include <stdio.h>
#include <stdlib.h>
/* Declaring functions */
int sorting_sign(int x);
double sorting_whole(double x);
double sorting_fract(double x);
/* Calling main function */
int main()
{
double num, fractures; /* declaring variables */
int sign_sorted, part;
double whole_sorted;
printf("LET ME TELL YOU SOME INTERESTING STUF ABOUT YOUR NUMBER!\n\n");
printf("Enter your number: ");
scanf("%lf", &num);
sign_sorted = sorting_sign(num); /* Calling the function that sorts out if this number is '+' or '-' */
whole_sorted = sorting_whole(num); /* Calling the function separating whole number from decimals */
fractures = sorting_fract(num); /* Calling the function removing the whole number from the fractures */
printf("Sign: %c\nWhole: %0.lf\nFraction: %f", sign_sorted, whole_sorted, fractures);
return 0;
}
/* Function for sorting of if number is '+' or '-' */
int sorting_sign(int x)
{
int sign;
/* true if number is less than 0 */
if(x < 0.0){sign = '-';}
/* true if number is greater than 0 */
else if(x > 0.0){sign = '+';}
return (sign);
}
/* Function for sorting out the whole number */
double sorting_whole (double x)
{
int whole;
whole = x;
return (whole);
}
/* Function for sorting out the fractions */
double sorting_fract(double x)
{
int whole;
double fract;
whole = (int)x;
fract = x - whole;
return (fract);
}

Determining if a float has a fractional part?

Here is the problem: The game Totals can be played by any number of people. It starts with a total of 100 and each player in turn makes an integer displacement between -20 and 20 to that total. The winner is the player whose adjustment makes the total equal to 5. Using only the three variables given:
total
adjustment
counter
Here is what I have so far:
#include <stdio.h>
int main (void)
{
int counter=0;
float adj;
int ttl=100;
printf("You all know the rules now lets begin!!!\n\n\nWe start with 100. What is\n");
while (ttl!=5)
{
printf("YOUR ADJUSTMENT?");
scanf("%f",&adj);
counter++;
if (adj<=20 && adj>=-20)
{
ttl=ttl+adj;
printf("The total is %d\n",ttl);
}
else
{
printf ("I'm sorry. Do you not know the rules?\n");
}
}
printf("The game is won in %d steps!",counter);
}
What I need:
When a decimal number is entered it goes to the else. How do I determine if a float has a fractional part.
You can cast the float to an int and then compare it to your original variable. If they are the same there was no fractional part.
By using this method, there is no need for a temporary variable or a function call.
float adj;
....
if (adj == (int)adj)
printf ("no fractional!\n");
else
printf ("fractional!\n");
Explanation
Since an int cannot handle fractions the value of your float will be truncated into an int (as an example (float)14.3 will be truncated into (int)14).
When comparing 14 to 14.3 it's obvious that they are not the same value, and therefore "fractional!" will be printed.
#include <stdio.h>
#include <math.h>
int main ()
{
float param, fractpart, intpart;
param = 3.14159265;
fractpart = modff (param , &intpart);
return 0;
}
http://www.cplusplus.com/reference/clibrary/cmath/modf/
modff finds the fractional part, so I guess testing whether it's equal to 0 or null will answer your question.
if you want to know whether a real number x has no fractional part, try x==floor(x).
I am only learning C so tell me if I am wrong, please.
But if instead of using
scanf("%f",&adj);
if you use:
scanf("%d%d", &adj, &IsUndef);
Therefore if the user typed anything other than a whole integer &IsUndef would not equal NULL and must have a fractional part sending the user to else.
maybe.
Using scanf() is problematic. If the user typed -5 +10 -15 -15 on the first line of input, then hit return, you'd process the 4 numbers in turn with scanf(). This is likely not what you wanted. Also, of course, if the user types +3 or more, then the first conversion stops once the space is read, and all subsequent conversions fail on the o or or, and the code goes into a loop. You must check the return value from scanf() to know whether it was able to convert anything.
The read-ahead problems are sufficiently severe that I'd go for the quasi-standard alternative of using fgets() to read a line of data, and then using sscanf() (that extra s is all important) to parse a number.
To determine whether a floating point number has a fractional part as well as an integer part, you could use the modf() or modff() function - the latter since your adj is a float:
#include <math.h>
double modf(double x, double *iptr);
float modff(float value, float *iptr);
The return value is the signed fractional part of x; the value in iptr is the integer part. Note that modff() may not be available in compilers (runtime libraries) that do not support C99. In that case, you may have to use double and modf(). However, it is probably as simple to restrict the user to entering integers with %d format and an integer type for adj; that's what I'd have done from the start.
Another point of detail: do you really want to count invalid numbers in the total number of attempts?
#include <stdio.h>
#include <math.h>
int main(void)
{
int counter=0;
int ttl=100;
printf("You all know the rules now lets begin!!!\n"
"\n\nWe start with 100. What is\n");
while (ttl != 5)
{
char buffer[4096];
float a_int;
float adj;
printf("YOUR ADJUSTMENT?");
if (fgets(buffer, sizeof(buffer), stdin) == 0)
break;
if (sscanf("%f", &adj) != 1)
break;
if (adj<=20 && adj>=-20 && modff(adj, &a_int) == 0.0)
{
counter++; // Not counting invalid numbers
ttl += adj;
printf("The total is %d\n", ttl);
}
else
{
printf ("I'm sorry. Do you not know the rules?\n");
}
}
if (ttl == 5)
printf("The game is won in %d steps!\n", counter);
else
printf("No-one wins; the total is not 5\n");
return(0);
}
Clearly, I'm studiously ignoring the possibility that someone might type in more than 4095 characters before typing return.

convert char* to double with max 2 places after the point

i'm reading tokens from file, it enters the char pointers perfectly as it comes
in the file, but after sending it to this function:
double CharToDouble(char *ptemp)
{
if(ptemp != NULL)
{
if(ptemp[0] == '0')
return atof(ptemp);
else
return atof(ptemp)/100;
}
return 0;
}
the values i'm getting in the doubles where i save this function result are like 0.6600000000001
0.280000000000000000
and stuff like that, i want it to be ecaxtly as in the char*..
it's money issues, in cents.
any idea?
If it's a currency, multiply by 100 and round down to an integer, so instead of 123.45, you have 12345.
Note: Float and Double are accurate only up to a certain precision (machine precision), because not every real number can be encoded in the floating point format.
When you're only interested in output of the correct format, you must use the correct printf command, i.e.
double currency_value = 9.95;
printf("Currency: %.2f", currency_value)
Look up "Format String" to learn more. The %.2f says that I want a floating point number with a fixed position after the comma (f) and that this position should be the second number after the comma (2).

Resources