Right, i have a 2 files (Distance and time) that have different values on their rows, in the program that divides both values on line into their speed and displays on screen.
This works perfectly, however, the function gives the calculated value to the nearest whole number:
#include <stdio.h>
int main()
{
FILE *fTotDc;
FILE *fTotTc;
int CalScD; //Values for total cycling speed
int CalScT;
float CalScS;
char ScSValue[32];
int DataCount=1; //File line comparison
struct store06 //TICtotD
{
char defTotDc[16];
}stock06[512];
struct store08 //TICtotT
{
char defTotTc[16];
}stock08[512];
fTotDc=fopen("TICtotD.txt","r"); //Opens total distance
fscanf(fTotDc,"%16[^\n]%*.2f", stock06[DataCount].defTotDc);
fTotTc=fopen("TICtotT.txt","r"); //Opens total time
fscanf(fTotTc,"%16[^\n]%*.2f", stock08[DataCount].defTotTc);
printf("|Distance |Time |Speed |");
printf("\n");
printf("|%-16s", stock06[DataCount].defTotDc);
printf("|%-16s", stock08[DataCount].defTotTc);
CalScD = atoi(stock06[DataCount].defTotDc); //Totals are converted to int for calculation
CalScT = atoi(stock08[DataCount].defTotTc);
if(CalScT == 0) //Test for 1/0 error, There is also a failsafe in the edit function which checks for t=0;
{
if(CalScD == 0) //If distance is 0 (As it is by default), the speed is 0.
{
printf("|0 ");
}
else //If distance is not 0 , we have (1/0)*k, which doesn't exist.
{
printf("|Error, Time is 0");//Error message given.
}
}
else
{
CalScS = CalScD/CalScT;
snprintf(ScSValue,32,"%.2f", CalScS); //Turns this int value into a string
printf("|%-16s",ScSValue); //String outputted
}
printf("|"); //last column
getch();
}
This is the code for one line, given that this on a do-while loop until the end of the file.
Input (distance file): Line 1: 4 , (time file) Line 1: 1 .
Expected speed output: 0.25
Actual output: 0.00
Edit: My coding skills are RIP
Edit 2: The mistake, assuming interger/interger would automatically calculate a floating point value. I have changed the code accordingly, it works. Thank you guys.
In CalScS = CalScD/CalScT; first the integer division is executed, then the resulting value is converted to float and assigned to the variable.
Try this
CalScS = CalScD/(double)CalScT;
To first convert the denominator to floating point, then do the division and assign correctly.
Oh ... and (almost) always prefer double to float.
Your calculation line CalScS = CalScD/CalScT; is doing integer division, since both operands are integers.
You need one (or both) of the operands to be floats (or doubles) to get floating-point division.
In your code
int CalScD; //Values for total cycling speed
int CalScT;
both are of type int, and CalScS is of type float.
While calculating the division using
CalScS = CalScD/CalScT;
first, the division will be performed as integer division [resulting in an int value] and after that, the int result will be promoted to float. That's why you're getting the integer output.
change
CalScS = CalScD/CalScT;
to
CalScS = ((float)CalScD )/CalScT;
to enforce the floating point division.
Related
I was making a little program to test floats in the C: The program itself is very simple, I just want to based on the User's input, return how much Dollar(s), Quarter(s)... etc, his number has.
//------------------------------> First Part: All the necessary Variables <-----------------------------
int main (void)
{
//Getting the user Input
float number = get_float("Number: ");
//Checking if is a positive number
if (number < 0)
{
printf("A positive number, Please: ");
}
//Declaring my Constant/Temporary variables.
float coinValues[] = {1.00, 0.25, 0.10, 0.5, 0.01};
char *coinNames[] = {"Dollar(s): ", "Quarter(s): ", "Dime(s): ", "Nickel(s): ", "Penny(ies): "};
int i = 0;
int tmp = 0;
//-----------------------------------> Second Part: The code Itself <-----------------------------------
//Checking/Printing the necessary coins.
while (number > 0)
{
//Until the loop stops, check if the number can be divided by the CoinValue.
if (number >= coinValues[i])
{
//Print the current Coin Name from the divided value.
printf("%s", coinNames[i]);
//Check if the Current Number still contains Coin Values inside of it, if True counts one in your "Coin Score".
while (number >= coinValues[i])
{
number -= coinValues[i];
tmp++;
}
//Print the Current "Coin Score", then resets TMP.
printf("%i\n", tmp);
tmp = 0;
}
else
{
//Updating the Coin value
i++;
}
}
}
My program was running very well as long I use Integers, but when I converted this code for Floats the values (Dime(s), Nickel(s), and Penny(ies)) start to return non-expected results in the Int variable tmp.
An expected result for a number like 2.6, will be 2 Dollars, 2 Quarters, and 1 Dime, but sometimes, instead of use the Dime(s), the program skips them entire and make the operation with the Nickel(s), however, what is bugging me is that the program is always returning AWL=+ without any value and then the program stay froze forever.
Considering that my only thought is that I'm "suffering" from Float Imprecision, and I don't know how to solve it, so can anyone Help me?
Ps. The program needs to always return the maximum value from each coin before pass forward.
Floating-point arithmetic is designed to approximate real-number arithmetic. IEEE 754-2008 says “Floating-point arithmetic is a systematic approximation of real arithmetic…” So there is no way to “lock” decimal digits in binary floating-point. It is intended to be used where you want an approximation, such as modeling physics. That even includes some financial applications, such as options evaluation. Although floating-point arithmetic can be used for exact calculations in some situations, these require particular care and are generally only pursued in special circumstances.
So the answer to your question on how to lock decimal places is there is no good way to do that with binary floating-point. Attempting to do so generally just yields the same effects as integer arithmetic but less efficiently and with more difficult code. So use integer arithmetic and scale the amounts according to the smallest unit of currency desired, such as a penny.
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
#include<stdio.h>
#include<stdlib.h>
#include<math.h>
int main()
{
int i,a,n,r;
n=12345;
r=0;
for(i=4;i>=0;i--)
{
a=n%10;
n=n/10;
r=r+a*pow(10,i);
}
printf("%d",r);
return 0;
}
Current output - 54320
Expected output - 54321
Please advise on what I may change in my code to reflect the correct output.
The pow function returns a value of type double. Because this is a floating point type, the result it returns will not always be exact.
What's happening in this case is that on the last iteration of the loop pow(10, 0) returns a value slightly less than 1. This results in the right hand side of r=r+a*pow(10,i); to similarly be slightly less than 54321. When this value is then assigned to r, which is of type int, it gets truncated.
Rather than using the pow function here, use the following:
r=r*10+a;
This shifts the current digits in r over by 1, then adds the newest digit to the end. Also, rather than using a for loop, use while (n>0) instead. Then it doesn't matter how many digits you have.
while (n>0)
{
a=n%10;
n=n/10;
r=r*10+a;
}
Here is a simplified version of your algorithm:
void reverse_digits(int a) {
int b = 0;
while (a > 0) {
b = b * 10 + a % 10;
a /= 10;
}
printf("%d\n", b);
}
As for converting to character arrays as mentioned in the comments it's worth to notice that the convertion function will do similar arithmetic operations in order to convert the integer to character array, so doing the reversing using integers seems more convenient.
I am writing a program that reads wavelength and intensity data from separate signal and background files (so each file is comprised of a number of pairs of wavelength and intensity). As you can see, I do this by creating a structure, and then assigning the values to the proper elements in the structure using fscanf in a loop. Once the data is read in, the program is supposed to plot it on the interval where the recorded wavelengths in each file overlap, that is, the common range of wavelengths. The wavelengths align perfectly where this overlap exist and are known to be spaced at a constant difference. Thus, my way of discerning which elements of the structure array were applicable was to determine which of the two files' minimum wavelength was higher, and maximum wavelength was lower. Then, for the file that had the lower minimum and higher maximum, I would find the difference between this and the higher minimum/lower maximum, and then divide it by the constant step to determine how many elements to offset. This works, except when the math is done, the program returns a wrong answer that is completely inexplicable.
In the code below, I define the constant step as lambdastep by calculating the difference between wavelengths of one element and the element before it. With my sample data, it is .002, which is confirmed by printf. However, when I run the program and divide by lambdastep, I get an incorrect answer. When I run the program dividing by .002, I get the correct answer. Why is this case? There is no explanation I can think of.
#include<stdio.h>
#include<math.h>
#include<stdlib.h>
#include "plots.h"
struct spectrum{
double lambda;
double intensity;
};
main(){
double a=0,b=0,c=0,d=0,lambdastep,smin,smax,bmin,bmax,tmin,tmax,sintmin,bintmin,tintmin,sintmax,bintmax,tintmax,ymin,ymax;
int ns,nb,nt,i=0,sminel,smaxel,bminel,bmaxel,tminel,tmaxel;
double min(struct spectrum *a,int,int);
double max(struct spectrum *a,int,int);
FILE *Input;
Input = fopen("sig.dat","r");
FILE *InputII;
InputII = fopen("bck.dat","r");
fscanf(Input,"%d",&ns);
fscanf(InputII,"%d",&nb);
struct spectrum signal[ns];
struct spectrum background[nb];
struct spectrum *s = &signal[0];
struct spectrum *ba = &background[0];
s = malloc(ns*sizeof(struct spectrum));
ba = malloc(nb*sizeof(struct spectrum));
while( fscanf(Input,"%lf%lf",&a,&b) != EOF){
signal[i].lambda = a;
signal[i].intensity = b;
i++;
}
i = 0;
while( fscanf(InputII,"%lf%lf",&c,&d) != EOF){
background[i].lambda = c;
background[i].intensity = d;
i++;
}
for (i=0; i < ns ;i++){
printf("%.7lf %.7lf\n", signal[i].lambda,signal[i].intensity);
}
printf("\n");
for (i=0; i < nb ;i++){
printf("%.7lf %.7lf\n", background[i].lambda,background[i].intensity);
}
lambdastep = signal[1].lambda - signal[0].lambda; //this is where I define lambdastep as the interval between two measurements
smin = signal[0].lambda;
smax = signal[ns-1].lambda;
bmin = background[0].lambda;
bmax = background[nb-1].lambda;
if (smin > bmin)
tmin = smin;
else
tmin = bmin;
if (smax > bmax)
tmax = bmax;
else
tmax = smax;
printf("%lf %lf %lf %lf %lf %lf %lf\n",lambdastep,smin,smax,bmin,bmax,tmin,tmax); //here is where I confirm that it is .002, which is the expected value
sminel = (tmin-smin)/(lambdastep); //sminel should be 27, but it returns 26 when lamdastep is used. it works right when .002 is directly entered , but not with lambdastep, even though i already confirmed they are exactly the same. why?
sminel is an integer, so (tmin-smin)/lambdastep will be casted to an integer when the calculation concludes.
A very slight difference in lambdastep could be the difference between getting e.g. 27.00001 and 26.99999; the latter truncates down to 26 when cast to an int.
Try using floor, ceil, or round to get better control over the rounding of the returned value.
It almost certainly has to do with the inherent imprecision of floating-point calculations. Trying printing out lambdastep to many significant digits -- I bet you'll find that its exact value is slightly larger than you think it is.
With my sample data, it is .002, which is confirmed by printf.
Try printing out (lambdastep == .002).
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.