Modulus in C isn't working - c

So, I'm having a little problem with the following program:
#include <stdio.h>
int main()
{
int centimeters, feet, inches;
printf("Please enter an amount in centimeters\n");
scanf("%i", &centimeters);
getchar();
inches = (centimeters/2.54);
feet = inches % 12;
printf("\n%i", &feet);
return 0;
}
No matter what number I input, the program thinks that the answer is 2358852. I know for a fact that 24 centimeters is not more than 2 million feet. If it matters, I am using Dev C++ to compile.

This is wrong
printf("\n%i", &feet);
it should be
printf("\n%i", feet);
/* ^ no & here */
printf("\n%i", &feet); prints the address of feet, and not it's value.
Your program also assumes that the scanf()ed value was read successfuly, you must check the return value of scanf() to ensure that it succeeded
#include <stdio.h>
int main()
{
int centimeters, feet, inches;
printf("Please enter an amount in centimeters\n");
if (scanf("%i", &centimeters) == 1)
{
getchar();
inches = centimeters / 2.54;
feet = inches % 12;
printf("\n%i", feet);
}
return 0;
}
also, apparently the formula is wrong as mentioned in another answer, please check it.

Your modulus calculation for feet is wrong. It should be
feet = inches / 12;
inches %= 12;
printf("\n%i feet, %i inches", feet, inches);

Related

C - Adding Distance from User Input using struct

I am very new to C and am struggling with this code. I need to get the feet and inches of two athletes from user input using a structure, then total the inches of each athlete to determine the winner. The issue I'm having is that the value being returned doesn't make any sense. My guess is it has something to do with getting the address of the value instead of the actual value, but after changing some things around I just end up with errors or the program crashing. Any help is appreciated.
#include <stdio.h>
#include <stdlib.h>
//Distance Structure
struct Distance
{
int feet;
float inches;
};
int main() {
//Initialize athelete structures
struct Distance athlete1;
struct Distance athlete2;
//Get values for athlete 1
printf("Enter the distance for athlete 1\n");
printf("Feet: ");
scanf("%d", &athlete1.feet);
printf("Inches: ");
scanf("%d", &athlete1.inches);
//Get values for athlete 2
printf("Enter the distance for athlete 2\n");
printf("Feet: ");
scanf("%d", &athlete2.feet);
printf("Inches: ");
scanf("%d", &athlete2.inches);
//Convert values to inches
float total1 = calculateInches(athlete1.feet, athlete1.inches);
float total2 = calculateInches(athlete2.feet, athlete2.inches);
//Print distance in inches
printf("\nAthlete 1 has a distance of %d inches\n", total1);
printf("Athlete 2 has a distance of %d inches\n\n", total2);
//Print the winner
if(total1 > total2){
printf("Athlete 1 wins!");
}
else if(total1 < total2){
printf("Athlete 2 wins!");
}
else{
printf("Tie!");
}
return 0;
}
//Calculate Inches
int calculateInches(feet, inches){
float total;
total = (feet*12) + inches;
return total;
}
There are few issues with your code:
The format specifier to be used whenever you are using float is %f instead you are using %d
Try forward declaring your calculateInches() method. Write it above the main() method or try using a function prototype. have a look at this link
Mention the right types for the arguments to the function float calculateInches(float feet, int inches). Related question
Working example: https://ideone.com/jsMZgv

C Unhandled exception 0xC0000094: Integer division by zero

I have been given this error for two days straight, and I have worked on it for about three hours, altogether. When I run it, it will tell me how many $10 bills I need but just stops at the $5 line and gives me this exception every time.
#define _CRT_SECURE_NO_WARNINGS 'code'
#include <stdio.h>]
#include <stdlib.h>
#include "math.h"
int main()
{
int ten = 10;
int five = 5;
int one = 1;
float quarter = .25;
float dime = .10;
float nickel = .05;
float penny = .01;
double money=0;
printf("Please enter a monetary amount:");
scanf_s("%lf", &money);//scanning the entry in, and & is allowing it to be entered
//money is the input number
printf("You entered: %lf \n", money);//creates too many zeroes but for now move on
ten = money / ten;//dividing the change = 10, and then
money = (int) money % ten;//this determines how many tens there are in the mix
//casted it because it only needs to be an integer not a double
printf("$10 : %d \n", ten);//printing an integer of how many tens are needed to make up money
five = money / five;//dividing the change = 10, and then
money = (int) money % five;//this determines how many tens there are in the mix
//casted it because it only needs to be an integer not a double
printf("$5 : %d \n", five);
//first problemm I had was putting in const, and that gave me a bajillion errors
return(EXIT_SUCCESS);
}
The error that you have mentioned will be shown if you divide a number by zero.just like hanie mentioned in her answer but in your case i don't see a line were you are dividing a number by zero but you have some lines were you overwrite the ten and five variables using modulo operator i guess it might be throwing the error.
I am posting a modified version of your code. Hope it helps you.
#define _CRT_SECURE_NO_WARNINGS 'code'
#include <stdio.h>
#include <stdlib.h>
#include "math.h"
int main()
{
int tens = 0;
int fives = 0;
double money=0;
printf("Please enter a monetary amount:");
scanf("%lf", &money);
printf("You entered: %lf \n", money);
tens = money / 10;
printf("$10 : %d \n", tens);
money = money - tens * 10;
fives = money / 5;
printf("$5 : %d \n", fives);
money = money - fives * 5;
return(EXIT_SUCCESS);
}
Sample Input and Output
Please enter a monetary amount:125
You entered: 125.000000
$10 : 12
$5 : 1
Please enter a monetary amount:123
$10 : 12
$5 : 0
Note that most implementations of floating point math will follow a standard (e.g. IEEE 754), in which case operations like divide-by-zero will have consistent results and the C standard says the operation is undefined.
before doing division you need to do something like this:
if(denominator != 0)
a = a / denominator;
or
if(denominator != 0)
a = a % denominator;

How to force program to recognize word and stop

I have a problem related to different types of variables at the input type.
My program is simple. I type the temperature in Celsius, program prints Celsius and Fahrenheit temperature value and then loops itself asking for next value in Celsius. If you type "-99999" it will stop.
I wanted to change it to stop when I type a word "elo" (It basically means "Bye" in Polish slang :) ) but after a few hours of trying I gave up...
I'll appreciate any help!
#include <stdio.h>
float fahrenheit(long);
int main()
{
int celsius;
printf("Type the temperature in celsius: ", &celsius);
scanf_s("%ld", &celsius);
while (celsius != -99999) {
printf("%ld %6.1f\n", celsius, fahrenheit(celsius));
printf("Type the temperature in celsius: ", &celsius);
scanf_s("%ld", &celsius);
}
}
float fahrenheit(long celsius)
{
return (float) 1.8*celsius + 32.0;
}
There are a number of ways to do this. I think the easiest is to detect scanf failed to read a number and then fall back on string input.
int celcius;
char buff[10];
bool elo = false;
int args_read = scanf(" %d", &celcius);
if (args_read < 1) {
// User must have put in a non-number
scanf(" %s", buff);
if (strcmp(buff, "elo") == 0) {
elo = true;
}
}
The line printf("Type the temperature in celsius: ", &celsius); is strange. Didn't your compiler complain about this? Why are you providing the address of celsius as an argument to this call? Another mistake is scanf_s("%ld", &celsius);, which reads in celsius as a long int value, when you have only declared celsius as an int. It's a good idea to always enable compiler warnings when you're working on code.
As mentioned by #StephenDocy, you need to read in the input as a string first, then check to see if it is a number or your stop word.
You can also simplify your code a bit to avoid repeating lines like printf("Type the temperature in celsius: ", &celsius); more than necessary. I think it would also make sense to treat celsius as a floating point value
#include <stdio.h>
#include <string.h>
float fahrenheit(float);
int main() {
float celsius;
char input_buffer[256];
while (1) {
printf("Type the temperature in celsius:\n");
scanf("%255s", input_buffer);
if (strcmp("elo", input_buffer) == 0) break;
if (sscanf(input_buffer, "%f", &celsius) == 1) {
printf("%6.1f %6.1f\n", celsius, fahrenheit(celsius));
}
}
return 0;
}
float fahrenheit(float celsius) {
return 1.8 * celsius + 32.0;
}

Trying to write a code for a bill changer/coin vending kiosk

I'm trying to write a code for a bill changer where the amount of money inserted are converted back into coins for the user. The problem is I keep having decimals in my amount of 50c like 222.222 when i input 111.111. My 20c and 10c is unused.. Please help
#include <stdio.h>
int main()
{
double sum50c=0, sum20c=0, sum10c=0, remainder, remainder2, remainder3, end=0;
double amount;
do
{
printf("Please enter an amount(dollars):");
scanf("%lf", &amount);
amount=amount*100;
if(amount<0){
printf("Invalid Input\n");
printf("Re-enter your amount:");
scanf("%lf", &amount);
}
if(amount>=50){
remainder=amount/50;
sum50c=remainder;
}else
if(remainder!=0){
remainder2=remainder/20;
sum20c=remainder2;
}else
if(remainder2!=0){
remainder3=remainder3/10;
sum10c=remainder3;
}
if(sum50c>200||sum20c>200||sum10c>200){
end++;
}else{
end=0;
}
}
while(end<=0);
printf("The amount of 50cents=%lf, 20cents=%lf, 10cents=%lf", sum50c, sum20c, sum10c);
}
There are basically two errors in your code:
Don't operate on floating-point numbers here. The number of coins will be a discrete number, which should be represented as int or maybe even unsigned int. The amount itself may be read in as floating-point number for simplicity, but it should also be converted to the number of cents as integerin order to avoid rounding errors.
You have to find combinations of coins: 30c is 1%times;20c + 1×10c. That means that you can't use else if chains, which will only consider one type of coin. Treat all types of coin, highes denomination first, and then reduce the amount still to handle. Note that with 10c as smallest coin, you might not be able to give full change for all amounts.
Here's you example without the outer loop and without the strange end business:
#include <stdlib.h>
#include <stdio.h>
int main()
{
int num50c = 0,
num20c = 0,
num10c = 0;
int amount; // amount in cents
double iamount; // input amount in dollars
printf("Please enter an amount: ");
scanf("%lf", &iamount);
amount = iamount * 100 + 0.5;
if (amount < 0) {
printf("Invalid Input\n");
exit(1);
}
num50c = amount / 50;
amount %= 50;
num20c = amount / 20;
amount %= 20;
num10c = amount / 10;
amount %= 10;
printf("%d x 50c = %d\n", num50c, num50c * 50);
printf("%d x 20c = %d\n", num20c, num20c * 20);
printf("%d x 10c = %d\n", num10c, num10c * 10);
printf("Remainder: %dc\n", amount);
return 0;
}
To force amount to have integer values you should round the value after your division:
if(amount>=50)
{
remainder=round(amount/50);
sum50c=remainder;
}

change counter c program not displaying correct output

I am working on a change counter program and I am stuck, I have searched here and 2 other coding forums, google and youtube, but haven't found an answer yet...my program sucks and i am brand new to c/c++...my txt book is not here yet so I am trying to read every every thing i can get my hands on till it gets here
This is what the output should be in the console window:
Welcome to Change Counter by Jo Mama!!
Please enter the total amount of purchase: $52.173
$52.173
Please enter amount of money tendered: $60
$60.00
Your change is: $7.83
-------------------------------------------
Twenties : 0
Tens : 0
Fives : 1
Ones : 2
Quarters : 3
Dimes : 0
Nickels : 1
Pennies : 3
-------------------------------------------
Thank you for using Change Counter!
here is what i have so far...
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int main(void)
{
// define variables here
long double numberOfTwenties = 0;
long double numberOfTens = 0;
long double numberOfFives = 0;
long double numberOfOnes = 0;
long double numberOfQuarters = 0;
long double numberOfDimes = 0;
long double numberOfNickels = 0;
long double numberOfPennies = 0;
double purchasePrice = 0;
double amountTendered = 0;
double amountOfChange = 0;
double amountOfChangeCents = 0;
// start program here
printf("Welcome to the change counter by Josh Manion!!\n\n");
printf("Please enter the total amount of purchase: $");
scanf("%d", &purchasePrice);
printf("%d\n", purchasePrice);
printf("Please enter amount of money tendered: $");
scanf("%d", &amountTendered);
printf("%d\n", amountTendered);
//do change calculations here
amountOfChange = (amountTendered - purchasePrice);
printf("Your change is: $%d\n", amountOfChange);
numberOfTwenties = amountOfChange / 20;
//amountOfChange = numberOfTwenties %= amountOfChange;
numberOfTens = (amountOfChange / 10);
numberOfFives = (amountOfChange / 5);
numberOfOnes = (amountOfChange / 1);
numberOfQuarters = (amountOfChange * 0.25);
// print change calculations here
printf("---------------------------------------------\n");
//display denominations of change here
printf("Twenties: %d\n", numberOfTwenties);
printf("Tens: %d\n", numberOfTens);
printf("Fives: %d\n", numberOfFives);
printf("Ones: %d\n", numberOfOnes);
printf("Quarters: %d\n", numberOfQuarters);
printf("Dimes: %d\n", numberOfDimes);
printf("Nickels: %d\n", numberOfNickels);
printf("Pennies: %d\n", numberOfPennies);
printf("---------------------------------------------\n");
printf("Thank you for using the Change Counter!");
getchar();
return EXIT_SUCCESS;
}
The problem is that my program doesn't work, it shows the change after the prompt but not the breakdown of denominations, I am sposed to use the "%" to bring down the change amount, but i havent found any examples. I don't know what else to say... besides I'm new and this post will help a lot of people...
Your program has undefined behaviour : you must use %Lf as the printf modifier to print a long double (same issue with your usage of scanf)

Resources