Why the variable time1 becoming Zero? - c

When I am getting some problem why time1 variable getting zero. right after calculation of floor.
#include <stdio.h>
#include <stdlib.h>
#include <windows.h>
int main()
{
int curfl = 0, destfl, floor;
int time1, high, speed;
high = 3;
speed = 5;
while(1)
{
printf("Currently the elevator is at floor number = %d\n", curfl);
printf("Enter the floor number between 0-25 : ");
scanf("%d", &destfl);
if(destfl > curfl)
{
floor = destfl - curfl;
/*****************************/
time1 = (floor * (high / speed)); //variable become zero here
/*****************************/
printf("Elevator will take %d second to reach %d (st, nd, rd) floor \n", time1, destfl);
while(curfl != destfl)
{
Sleep(1000 * 3 / 5);
curfl++;
printf("You are at floor number %d \n", curfl);
}
printf("Door opening \n");
Sleep(10000);
printf("Door Closed\n");
}
else if(destfl > curfl)
{
floor = curfl - destfl;
time1 = (floor * (3 / 5));
printf("Elevator will take %d second to reach %d (st, nd, rd) floor \n", time1, destfl);
while(curfl != destfl)
{
Sleep(1000 * 3 / 5);
curfl--;
printf("You are at floor number %d \n", curfl);
}
printf("Door opening \n");
Sleep(10000);
printf("Door Closed\n");
}
else{
printf("You are the same floor. Please getout from the elevator \n");
}
}
// printf("Hello world!\n");
return 0;
}

You are doing integer calculations. Switch to something that handles fractions.

You are running into integer division. When you do arithmetic on integers, and the result will also be an integer. So something like 1 / 3 = 0 in integer-land. So when you do (high / speed), the temporary result will be an integer, and if the answer is some decimal < 1, the result will be truncate simply to 0.
To fix this, you should change the code to use float or double instead int.

calculate time1 like follows :
int curfl = 0, destfl, floor;
int high;
float speed, time1;
................................
time1 = (floor * (high / speed));
It looks like its for an embedded device. So don't know how it supports floating point operation.
if it does not support, pickup a divide algorithm, declare a type like following :
struct myfloat{
int precision;
int exponent;
}
and then write a divide function like :
struct myfloat * divide(int a, int b) /* gives result for a/b */

Related

Logarithm calculator

I'm trying to make a logarithm calculator and got stuckā€”it doesn't print out a value. The problem may be at lines 15 or 24 or both. How can I make it print the value (all written in C).
Here's the full code:
#include <stdio.h>
#include <stdlib.h>
// Finds base 10 logarithms
int main()
{
float result;
float base = 10.0;
float multiplier = 1.0;
// float counter1 = 0.0;
// float counter2 = 0;
printf("Input result: ");
scanf("%l", result);
// Solves for all results above the base
if(result > base) {
while(result > multiplier) {
multiplier = multiplier * multiplier; // the multiplier has to check non-whole numbers
multiplier += 0.001;
} // division
}
printf("Your exponent is: %l \n", &multiplier);
printf("Hello mathematics!");
return 0;
}
All help appreciated,
Xebiq
you should delete & in printf,and add & in scanf.
printf("Your exponent is: %f \n", multiplier);
scanf("%f", &result);
and use %f in them.
and with base 10 I suggest this function to calculate log:
unsigned int Log2n(unsigned int n)
{
return (n > 1) ? 1 + Log2n(n / 10) : 0;
}
also you should know about Floating-point numbers here:
multiplier += 0.001;
probably exactly 0.001 won't be added to multiplier when I debugged this 0.00100005 was being add to multiplier in my compiler.(which will affect multiplying)
In printf remove '&' and in scanf add '&' before variable.

Bug in While-Loop Keeps Counting Beyond Condition

For school I am to write a C program that takes some amount of cash and returns the smallest number of coins it would take to reach that amount. I don't know what I am doing wrong. I've been tweaking and trying all sorts of different things but I cannot seem to totally debug the program.
The program gives correct answers to some inputs but overstates the amount of coins needed for many inputs.
Here is what I have so far.
#include <stdio.h>
int main()
{
float cash;
int n;
int counter=0;
int quarters=0;
int dimes=0;
int nickels=0;
int pennies=0;
for (;;)
{
printf("Enter change amount: ");
scanf("%f",&cash);
if (cash > 0)
{
break;
}
}
n = cash * 100;
counter = 0;
while (n > 0)
{
while (n >= 25)
{
counter ++;
n = n - 25;
quarters ++;
printf("%i\n",n);
}
while (n >= 10 && n < 25)
{
counter ++;
n = n - 10;
dimes ++;
printf("%i\n",n);
}
while (n >= 5 && n < 10)
{
counter ++;
n = n - 1;
nickels++;
printf("%i\n",n);
}
while (n > 0 && n < 5)
{
counter ++;
n = n - 1;
pennies ++;
printf("%i\n",n);
}
}
printf("%d\n",counter + n);
printf("%i quarters, %i dimes, %i nickels, %i pennies\n",
quarters, dimes, nickels, pennies);
return 0;
}
I'm a bit surprised they're wanting you to use break to exit a loop, as you usually want loops to conclude "naturally" (and you usually save breaks for switch statements). Something like this should work, using integer division and the modulus operator (edit note: I'm using two ints instead of a single float because of inaccuracy with the latter. If someone more knowledgeable wants to show how to do it with float, would be interesting.):
#include <stdio.h>
int main() {
int dollar, cent;
int q = 0;
int d = 0;
int n = 0;
int p = 0;
int re;
printf("Enter amount: ");
scanf(" %d.%d", &dollar, &cent);
q = dollar * 4;
re = cent;
q = q + (re / 25);
re = re % 25;
d = re / 10;
re = re % 10;
n = re / 5;
re = re % 5;
p = re;
printf("q %d d %d n %d p %d\n", q, d, n, p);
return 0;
}
This approach also works if, for example, you're given the seconds and want to find the min:sec from that. If you're given 65 seconds, you do 65 / 60 for the minutes portion (which is 1), and the seconds portion is just the remainder after you divide by 60, or 65 % 60 (which is 5).
Here is a more complete answer that fits with the code that you gave us to start with. I changed the loops to subtraction/multiplication and fixed the bug where you were treating nickels as pennies. You don't need the counter variable anymore, but I left it in.
#include <stdio.h>
int main()
{
float cash;
int n;
int counter=0;
int quarters=0;
int dimes=0;
int nickels=0;
int pennies=0;
for (;;)
{
printf("Enter change amount: ");
scanf("%f",&cash);
if (cash > 0)
{
break;
}
}
n = cash * 100;
counter = 0;
if (n > 0)
{
quarters = (int)floor(n / 25);
n -= quarters*25;
printf( "%i\n", n );
dimes = (int)floor(n / 10);
n -= dimes*10;
printf("%i\n",n);
nickels = (int)floor(n / 5);
n -= nickels*5;
printf("%i\n",n);
pennies = n;
printf("%i\n",n);
}
printf("%i quarters, %i dimes, %i nickels, %i pennies\n",
quarters, dimes, nickels, pennies);
return 0;
}
First of all, try start with abstracting out how to handle one type of coin:
int coinsNeeded( int amount, int coinAmount )
{
return (int) floor( amount / coinAmount );
}
Then, handle each coin separately:
quarters = coinsNeeded( cash, 25 );
cash -= (quarters * 25);
Just repeat that for each type of coins you want to consider, and then print out the information at the end. There is some disagreement about whether you want to use floating points or not. Floating points do have rounding errors that you want to avoid when using money. what you actually need is a fixed point data type, but I digress. You can get close enough by doing it the way you're doing it (multiplying by 100 and just dealing with pennies).

Error: invalid operands to binary expression ('float' and 'float')

I apologize if this question has been asked before. I looked around and was not able to find a solution, I am new to C.
I understand that I am not able to get a % from a float. How would I be able to capture the remainder of this math, if I am using 2 floats?
#include <cs50.h>
#include <stdio.h>
#include <ctype.h>
#include <math.h>
/*
** Always use the largest coin possible
** keep track of coins used
** Print the final amount of coins
*/
int main (void)
{
float change;
int counter = 0;
int division;
//float rem;
float quarter = 0.25;
//float quarter = 0.25, dime = 0.10, nickel = 0.05, penny = 0.01;
/* Prompt user for an amont of change*/
do{
printf("How much do we owe you in change? ");
change = GetFloat();
}
while (change <= 0);
if (change >= quarter)
{
division = (change / quarter);
counter += division;
//change = (int)(change % quarter);
printf("change: %.2f\n", change);
printf("counter: %d\n ", counter);
}
return (0);
}
You may want to check
fmod.
You can also do something like change = change - (int)(change / quarter) * quarter
You could implement the modulo yourself:
https://en.wikipedia.org/wiki/Modulo_operation
int a = (int)(change / quarter);
int mod = (int)(change - (quarter * a));
Also it might be possible to do it this way:
long mod = ((long)(change * 1000) % (long)(quater * 1000));
depending on the precision of your floats modify the 1000 and think about dividing the result by 1000!
But maybe it would be better to rethink what you really want as result?
Just scale up all your variable by 100 and then use integers instead of float.
#include <cs50.h>
#include <stdio.h>
#include <ctype.h>
#include <math.h>
/*
** Always use the largest coin possible
** keep track of coins used
** Print the final amount of coins
*/
int main (void)
{
float change_f;
int change;
int counter = 0;
int division;
//float rem;
int quarter = 25;
//int quarter = 25, dime = 10, nickel = 5, penny = 1;
/* Prompt user for an amont of change*/
do{
printf("How much do we owe you in change? ");
change_f = GetFloat();
}
while (change_f <= 0);
change = (int)(change_f*100);
if (change >= quarter)
{
division = (change / quarter);
counter += division;
//change = (int)(change % quarter);
printf("change: %.2f\n", change_f);
printf("counter: %d\n ", counter);
}
return (0);
}
NOTE: Choose scale factor according to the input precision i.e if it is 3 decimal digits then choose 1000 and so on.

Wrong calculation for decimal amount in C language

I'm trying to calculate the decimal amount in float but it won't calculate if the input is "0.01". However, it will calculate if the input is "0.02" but with wrong calculation. Here is the code:
#include <stdio.h>
#include <cs50.h>
float MCounting = 0.00;
int MAmountCoin = 0;
float MAmountUsed = 0.00;
int MCoinCount = 0;
float MRemainAmount = 0;
int MCoinOut = 0;
int MTotCoinOut = 0;
int main(void)
{
float Amount;
float MRemainAmount;
do
{
printf("Specify the amount you want in change: ");
Amount = GetFloat();
MRemainAmount = Amount;
}
while (Amount < 0 );
if (MRemainAmount > 0 || MRemainAmount < .05 )
printf ("\n\n ***** Calculatin for 0.01 *****\n");
{
printf ("MRemainAmount Before calculation: %.2f\n",MRemainAmount);
MCoinOut = MRemainAmount / .01;
printf ("MCoinOut = %i...MTotCoinOut = %i\n",MCoinOut,MTotCoinOut);
MRemainAmount = MRemainAmount - (MCoinOut * .01);
printf ("MRemainAmount = %.2f\n",MRemainAmount);
MTotCoinOut = MCoinOut + MTotCoinOut;
printf ("MTotCoinOut = %i\n",MTotCoinOut);
}
{ printf("Total Coin Out%i\n",MTotCoinOut); }
}
What's going wrong and how can I fix it?
You are hitting your epsilon limit. Since you are using floats you are limited in representation by FLT_EPSILON; if you were using a double, you would see improved resolution of DBL_EPSILON. (These values are from <float.h>)
#define DBL_EPSILON 2.2204460492503131e-016 /* smallest such that 1.0+DBL_EPSILON != 1.0 */
#define FLT_EPSILON 1.192092896e-07F /* smallest such that 1.0+FLT_EPSILON != 1.0 */
Thus if you are using a value like 10000, roughly, you're smallest change in value is something in the vicinity of 10000 * FLT_EPSILON, which would be about .012. If you want to represent with better precision, use doubles.
It is due to the imprecise representation of floating point numbers in the computers memory.
Read up on http://docs.oracle.com/cd/E19957-01/806-3568/ncg_goldberg.html

Need help programming with Mclauren series and Taylor series?

Ok so here's what i have so far:
#include <stdio.h>
#include <math.h>
//#define PI 3.14159
int factorial(int n){
if(n <= 1)
return(1);
else
return(n * factorial(n-1));
}
void McLaurin(float pi){
int factorial(int);
float x = 42*pi/180;
int i, val=0, sign;
for(i=1, sign=-1; i<11; i+=2){
sign *= -1; // alternate sign of cos(0) which is 1
val += (sign*(pow(x, i)) / factorial(i));
}
printf("\nMcLaurin of 42 = %d\n", val);
}
void Taylor(float pi){
int factorial(int);
float x;
int i;
float val=0.00, sign;
float a = pi/3;
printf("Enter x in degrees:\n");
scanf("%f", &x);
x=x*pi/180.0;
printf("%f",x);
for(i=0, sign=-1.0; i<2; i++){
if(i%2==1)
sign *= -1.0; // alternate sign of cos(0) which is 1
printf("%f",sign);
if(i%2==1)
val += (sign*sin(a)*(pow(x-a, i)) / factorial(i));
else
val += (sign*cos(a)*(pow(x-a, i)) / factorial(i));
printf("%d",factorial(i));
}
printf("\nTaylor of sin(%g degrees) = %d\n", (x*180.0)/pi, val);
}
main(){
float pi=3.14159;
void McLaurin(float);
void Taylor(float);
McLaurin(pi);
Taylor(pi);
}
and here's the output:
McLaurin of 42 = 0
Enter x in degrees:
42
0.733038-1.00000011.0000001
Taylor of sin(42 degrees) = -1073741824
I suspect the reason for these outrageous numbers goes with the fact that I mixed up my floats and ints? But i just cant figure it out...!! Maybe its a math thing, but its never been a strength of mine let alone program with calculus. Also the Mclaurin fails, how does it equal zero? WTF! Please help correct my noobish code. I am still a beginner...
----Update----
#include <stdio.h>
#include <math.h>
//#define PI 3.14159
int factorial(int n){
if(n <= 1)
return(1);
else
return(n * factorial(n-1));
}
void McLaurin(float pi){
int factorial(int);
float x = 42*pi/180, val=0;
int i, sign;
for(i=1, sign=-1; i<11; i+=2){
sign *= -1; // alternate sign of cos(0) which is 1
val += (sign*(pow(x, i)) / factorial(i));
}
printf("\nMcLaurin of of sin(%f degrees) = %f\n", (x*180.0)/pi, val);
}
void Taylor(float pi){
int factorial(int);
float x;
int i;
float val=0, sign;
float a = pi/3;
printf("Enter x in degrees:\n");
scanf("%f", &x);
x=x*pi/180.0;
printf("%f",x);
for(i=0, sign=-1.0; i<2; i++){
if(i%2==0)
sign *= -1; // alternate sign of cos(0) which is 1
printf("%f",sign);
if(i%2==0)
val += (sign*sin(a)*(pow(x-a, i)) / factorial(i));
else
val += (sign*cos(a)*(pow(x-a, i)) / factorial(i));
printf("%d",factorial(i));
}
printf("\nTaylor of sin(%f degrees) = %f\n", (x*180.0)/pi, val);
}
main(){
float pi=3.14159;
void McLaurin(float);
void Taylor(float);
McLaurin(pi);
Taylor(pi);
}
Gives me weird error.
/usr/lib/gcc/i686-pc-cygwin/3.4.4/../../../../i686-pc-cygwin/bin/ld: cannot open output file a.exe: Device or resource busy
collect2: ld returned 1 exit status
Can anyone explain what's wrong now?
Some potential sources of error:
your value of pi doesn't have sufficient digits for even float accuracy;
in your function Maclaurin you have val as an integer, on which you perform division;
in Taylor you only use 2 terms in the series
I think ?
a few things jump out:
in McLauren you define val (your calculated value) as an int. try defining it as a float
in Taylor you are only flipping your sign every other time so it goes -1, 1, -1, -1, 1, 1 .... and so on
i think your formula for the Taylor series is incorrect, after refreshing myself on wikipedia, you shouldn't be calling sin or cos (because that's what you are trying to calculate)
good luck!
This one that have already been mentioned is definitely troublesome:
val should be a float in McLaurin()
In addition, you need to use %f or %g instead of %d when using printf() to print out your vals. That's ultimately why you're getting such crazy numbers: floats being interpreted as ints.
Also, in Taylor(), you need to change your two if statements to be
if(i%2==0)
because you are Taylor expanding sin, not cos.
Doing these things yields 0.669130 and 0.708945 for the MacLaurin and Taylor series answers, respectively, using the same number of terms as in your code. If I add two more terms to the Taylor series answer (use i<4 instead of i<2), I get 0.668793. The true answer (using the same pi as you used) is 0.669130 which the Taylor series answer gets to with 3 more additional terms added in.

Resources