I am trying to make a program within code::blocks that will allow me to select multiple unit conversions to do. However, whenever I build and compile and reach the point in the program where it scans in my input for the variable "choice", code::blocks displays a window immediately afterwards that says that my .exe has stopped working and I can't figure out why this is the case. I am using the GNU GCC Compiler. Any help would be enormously appreciated.
#include <stdio.h>
int main()
{
float fahrenheit;
float celsius;
float pound;
float kilogram;
float inch;
float centimeter;
float mph;
float kph;
int foc;
int pok;
int ioc;
int mok;
int choice;
printf("\n1. Temperature Conversion\n");
printf("\n2. Weight Conversion\n");
printf("\n3. Length Conversion\n");
printf("\n4. Speed Conversion\n");
printf("\n5. Exit Program\n");
printf("\n");
printf("\nEnter the number of the program you would like to run :\n");
printf("\n");
scanf("%d", choice);
//Temperature Conversion
if(choice == 1) {
printf("\n1. Convert from Celsius to Fahrenheit\n");
printf("\n2. Convert from Fahrenheit to Celsius\n");
printf("\nEnter the number that corresponds with the conversion you would like to do:\n");
printf("\n");
scanf("%d", &foc);
if(foc == 1) {
//option 1
printf("\nEnter your temperature in Celsius : ");
scanf("%f", &celsius);
fahrenheit = 32 + (celsius * 1.8);
printf("\nYour temperature in Fahrenheit : %f ", fahrenheit);
}
else {
//option 2
printf("\nEnter your temperature in Fahrenheit : ");
scanf("%f", &fahrenheit);
celsius = (fahrenheit - 32) * 0.55555555;
printf("\nYour temperature in Celsius : %f ", celsius);
}
}
//Weight Conversion
else if(choice == 2) {
printf("\n1. Convert from Pound to Kilogram ");
printf("\n2. Convert from Kilogram to Pound ");
printf("\nEnter the number that corresponds with the conversion you would like to do: ");
printf("\n ");
scanf("%d", &pok);
if(pok == 1) {
//option 1
printf("\nEnter your weight in pounds : ");
scanf("%f", £);
kilogram = (2.20462 * pound);
printf("\nYour weight in kilograms : %f ", kilogram);
}
else {
//option 2
printf("\nEnter your weight in kilograms : ");
scanf("%f", &kilogram);
pound = (kilogram/2.20462);
printf("\nYour weight in pounds : %f ", celsius);
}
}
//Length Conversion
else if(choice == 3) {
printf("\n1. Convert from inches to centimeters ");
printf("\n2. Convert from centimeters to inches ");
printf("\nEnter the number that corresponds with the conversion you would like to do: ");
printf("\n ");
scanf("%d", &ioc);
if(ioc == 1) {
//option 1
printf("\nEnter your length in inches : ");
scanf("%f", &inch);
centimeter = (inch/2.54);
printf("\nYour length in centimeters : %f ", centimeter);
}
else {
//option 2
printf("\nEnter your length in centimeters : ");
scanf("%f", ¢imeter);
inch = (centimeter*2.54);
printf("\nYour length in inches : %f ", inch);
}
}
//Speed Conversion
else if(choice == 4) {
printf("\n1. Convert from mph to kph ");
printf("\n2. Convert from kph to mph ");
printf("\nEnter the number that corresponds with the conversion you would like to do: ");
printf("\n ");
scanf("%d", &mok);
if(mok == 1) {
//option 1
printf("\nEnter your speed in mph : ");
scanf("%f", &mph);
kph = (mph/1.60934);
printf("\nYour speed in kilometers: %f ", kph);
}
else {
//option 2
printf("\nEnter your speed in kph : ");
scanf("%f", &kph);
mph = (1.60934*kph);
printf("\nYour length in inches : %f ", mph);
}
}
else if(choice == 5) {
printf("\nProgram has ended. Thanks for your time!");
}
else {
printf("\nThat is not a valid program number. ");
}
}
You have to pass the pointer to the choice variable (i.e. &choice) to your scanf() call, just as you've done for your other scanf() uses.
I.e. instead of
scanf("%d", choice);
use
scanf("%d", &choice);
scanf() reads a value from the user and the address of the variable must be represented in the syntax
if not represented the program takes the garbage value so
Related
I'm a beginner to C language and I'm writing through a practice question where I use functions to convert between Fahrenheit and Celsius. I have written the program using 2 functions: one to convert from Fahrenheit to Celsius and another vice verca:
#include <stdio.h>
int celsius2fahrenheit(int celsius, int fahrenheit){
fahrenheit = (9/5) * celsius + 32;
printf("%d", fahrenheit);
}
int fahrenheit2celsius(int fahrenheit, int celsius){
celsius = (fahrenheit - 32) * (5/9);
printf("%d", celsius);
}
int main(void){
int celsius, fahrenheit;
celsius = fahrenheit = 0;
printf("-----------------Menu-----------------\n");
printf("Option 1. Convert Celsius to Fahrenheit\n");
printf("Option 2. Convert Fahrenheit to Celsius\n");
printf("\n");
printf("Option: ");
int Option;
scanf("%d", Option);
if (Option == 1){
printf("Enter the temperature (Celsius) : ");
scanf("%d", celsius);
printf("\n");
celsius2fahrenheit(celsius, fahrenheit);
}
else if (Option == 2){
printf("Enter the temperature (Fahrenheit) : ");
scanf("%d", fahrenheit);
printf("\n");
fahrenheit2celsius(fahrenheit, celsius);
}
else {
printf("Invalid Option");
}
return 0;
}
When the program was compiled, the error messages occur:
"Segmentation fault" after executing the option to select the operation. I assume there was something wrong with the variable declaration but I'm not too sure.
You are missing '&' in your scanf functions (line 23, 27 and 33)
Also you should take the values as floats to get more accurate results, because right now answers comes as integer..
#include <stdio.h>
int main()
{
float fh,cl;
int choice;
printf("\n1: Convert temperature from Fahrenheit to Celsius.");
printf("\n2: Convert temperature from Celsius to Fahrenheit.");
printf("\nEnter your choice (1, 2): ");
scanf("%d",&choice);
if(choice ==1){
printf("\nEnter temperature in Fahrenheit: ");
scanf("%f",&fh);
cl= (fh - 32) / 1.8;
printf("Temperature in Celsius: %.2f",cl);
}
else if(choice==2){
printf("\nEnter temperature in Celsius: ");
scanf("%f",&cl);
fh= (cl*1.8)+32;
printf("Temperature in Fahrenheit: %.2f",fh);
}
else{
printf("\nInvalid Choice !!!");
}
return 0;
}
scanf needs the specifier and the memory address of the variable.
scanf("%d", &Option);
Note that Option and &Option are two different things. & means the memory address where the variable is located.
Change each one in the code (line 27 and 33).
I'm trying get the variables: float managerTotal, hourlyTotal, commissionTotal, and pieceworkerTotal from their respective functions to print in the switch statement case: 'q' in the choiceInput function. Yesterday I had lots and lots of errors and now I have them passing through but when I enter an input for the variables it doesn't pass the value through, they only return as 0. Please can someone help explain what I'm doing wrong. Thank you.
Here is the code:
#include<stdio.h>
#include<conio.h>
void welcome() {
printf("-----------------------------------------------\n");
printf("Welcome to the Factory A Payroll\n");
}
void choosePayroll() {
printf("-----------------------------------------------\n");
printf("Press '1' to access the Manager's payroll\n");
printf("Press '2' to access the Hourly worker's payroll\n");
printf("Press '3' to access Commission worker's payroll\n");
printf("Press '4' to access Pieceworkers's payroll\n");
printf("Press 'Q' to access Manager's payroll\n");
printf("-----------------------------------------------\n");
choiceInput();
}
float managerIntro() {
float managerTotal;
char charReturn = 0;
printf("-----------------------------------------------\n");
printf("You have selected 'Manager's payroll'\n");
printf("-----------------------------------------------\n");
printf("Please enter your fixed weekly salary: $");
scanf_s("%f", &managerTotal);
printf("-----------------------------------------------\n");
printf("You have entered $%.2f as the weekly fixed salary\n", managerTotal);
printf("-----------------------------------------------\n");
printf("Press 'R' to return back to the main menu\n\n");
scanf_s(" %c", &charReturn); // space before %c to tell scanf to skip the leading whitespace
switch (charReturn)
{
case 'r':
choosePayroll();
default:
printf("You have entered an invalid key, press any key to try again\n");
getchar();
getchar();
hourlyIntro();
}
return managerTotal;
}
float hourlyIntro() {
char charReturn = 0;
float hourlyWage = 0;
float hoursWorked = 0;
float overTimeHours = 0;
float normalPay = 0;
float overTimePay = 0;
float hourlyTotal;
printf("-----------------------------------------------\n");
printf("You have selected 'Hourly worker's payroll'\n");
printf("-----------------------------------------------\n");
printf("Please enter the hourly wage for the worker: $");
scanf_s("%f", &hourlyWage);
printf("-----------------------------------------------\n");
printf("You have entered $%.2f as the hourly wage.", hourlyWage);
printf("\n-----------------------------------------------");
printf("\nPlease enter how many hours the worker has worked this week: ");
scanf_s("%f", &hoursWorked);
printf("\n-----------------------------------------------");
if (hoursWorked > 40) {
overTimeHours = hoursWorked - 40;
hoursWorked = 40;
}
normalPay = hourlyWage * hoursWorked;
overTimePay = (hourlyWage * 1.5) * overTimeHours;
hourlyTotal = normalPay + overTimeHours;
printf("\nNormal weekly pay : $%.2f\nOvertime weekly pay: $%.2f\n\nTotal weekly pay: $%.2f\n\n", normalPay, overTimePay, hourlyTotal);
printf("Press 'R' to return back to the main menu\n");
scanf_s(" %c", &charReturn); // space before %c to tell scanf to skip the leading whitespace
switch (charReturn)
{
case 'r':
choosePayroll();
default:
printf("You have entered an invalid key, press any key to try again\n");
getchar();
getchar();
hourlyIntro();
}
return hourlyTotal;
}
float commissionIntro() {
char charReturn = 0;
float basicSalary = 250;
float itemAPrice = 0;
float itemBPrice = 0;
float itemCPrice = 0;
float itemAQuantity = 0;
float itemBQuantity = 0;
float itemCQuantity = 0;
float itemACommission = 0;
float itemBCommission = 0;
float itemCCommission = 0;
float totalCommission = 0;
float commissionTotal = 0;
printf("-----------------------------------------------\n");
printf("You have selected 'Commission worker's payroll'\n");
printf("-----------------------------------------------\n");
printf("Please enter the price of Item A: $");
scanf_s("%f", &itemAPrice);
printf("-----------------------------------------------\n");
printf("Please enter the quantity of Item A sold this week: ");
scanf_s("%f", &itemAQuantity);
printf("-----------------------------------------------\n");
printf("Please enter the price of Item B: $");
scanf_s("%f", &itemBPrice);
printf("-----------------------------------------------\n");
printf("Please enter the quantity of Item B sold this week: ");
scanf_s("%f", &itemBQuantity);
printf("-----------------------------------------------\n");
printf("Please enter the price of Item C: $");
scanf_s("%f", &itemCPrice);
printf("-----------------------------------------------\n");
printf("Please enter the quantity of Item C sold this week: ");
scanf_s("%f", &itemCQuantity);
printf("\n-----------------------------------------------\n");
itemACommission = itemAQuantity * (itemAPrice * 0.057);
itemBCommission = itemBQuantity * (itemBPrice * 0.064);
itemCCommission = itemCQuantity * (itemCPrice * 0.072);
totalCommission = itemACommission + itemBCommission + itemCCommission;
commissionTotal = totalCommission + basicSalary;
printf("Commission for item A: $%.2f\n", itemACommission);
printf("Commission for item B: $%.2f\n", itemBCommission);
printf("Commission for item C: $%.2f\n", itemCCommission);
printf("Total commission: $%.2f\n", totalCommission);
printf("Total pay: $%.2f\n", commissionTotal);
printf("-----------------------------------------------\n");
printf("Press 'R' to return back to the main menu\n\n");;
scanf_s(" %c", &charReturn); // space before %c to tell scanf to skip the leading whitespace
switch (charReturn)
{
case 'r':
choosePayroll();
default:
printf("You have entered an invalid key, press any key to try again\n");
getchar();
getchar();
hourlyIntro();
}
return commissionTotal;
}
float pieceworkerIntro() {
char charReturn;
float quantityItem1;
float quantityItem2;
float quantityItem3;
float priceItem1 = 22.50;
float priceItem2 = 24.50;
float priceItem3 = 26;
float payItem1;
float payItem2;
float payItem3;
float pieceworkerTotal;
printf("-----------------------------------------------\n");
printf("You have selected 'Pieceworker's payroll'\n");
printf("-----------------------------------------------\n");
printf("Please enter the quantity of Item 1 produced this week: ");
scanf_s("%f", &quantityItem1);
printf("-----------------------------------------------\n");
printf("Please enter the quantity of Item 2 produced this week: ");
scanf_s("%f", &quantityItem2);
printf("-----------------------------------------------\n");
printf("Please enter the quantity of Item 3 produced this week: ");
scanf_s("%f", &quantityItem3);
printf("-----------------------------------------------\n");
payItem1 = quantityItem1 * priceItem1;
payItem2 = quantityItem2 * priceItem2;
payItem3 = quantityItem3 * priceItem3;
pieceworkerTotal = payItem1 + payItem2 + payItem3;
printf("\nItem 1 pay: $%.2f\nItem 2 pay: $%.2f\nItem 3 pay: $%.2f\n\nTotal pay: $%.2f", payItem1, payItem2, payItem3);
printf("Press 'R' to return back to the main menu\n\n");
scanf_s(" %c", &charReturn); // space before %c to tell scanf to skip the leading whitespace
switch (charReturn)
{
case 'r':
choosePayroll();
default:
printf("You have entered an invalid key, press any key to try again\n");
getchar();
getchar();
hourlyIntro();
}
}
void returnMenu() {
}
float choiceInput(float *managerTotal, float *hourlyTotal, float
*commissionTotal, float *pieceworkerTotal) {
char userChoice = 0;
scanf_s(" %c", &userChoice);
do {
switch (userChoice) {
case '1':
managerIntro();
break;
case '2':
hourlyIntro();
break;
case '3':
commissionIntro();
break;
case '4':
pieceworkerIntro();
break;
case 'q':
printf("Manager total is: $%.2f", &managerTotal);
printf("Hourly total is: $%.2f", &hourlyTotal);
printf("Commission total is: $%.2f", &commissionTotal);
printf("Pieceworker total is: $%.2f", &pieceworkerTotal);
exit(0);
default:
printf("You have entered an invalid key, please try again\n");
getchar();
getchar();
choosePayroll();
break;
}
} while (userChoice != 'Q');
}
int main(void) {
welcome();
choosePayroll();
return 0;
}
Note: I apologise it's longish code, but the reason I've kept it that way is because the last time I made it shorter it didn't end up working for my actual code, only the short code I posted as an example.
I made change in your code. Check it, if this change is not as per your requirement let me know.
#include <stdio.h>
float choiceInput();
void welcome();
void choosePayroll();
float managerIntro();
float hourlyIntro();
float commissionIntro();
float pieceworkerIntro();
float choiceInput();
int main()
{
welcome();
choosePayroll();
return 0;
}
void welcome()
{
printf("-----------------------------------------------\n");
printf("Welcome to the Factory A Payroll\n");
}
void choosePayroll()
{
printf("-----------------------------------------------\n");
printf("Press '1' to access the Manager's payroll\n");
printf("Press '2' to access the Hourly worker's payroll\n");
printf("Press '3' to access Commission worker's payroll\n");
printf("Press '4' to access Pieceworkers's payroll\n");
printf("Press 'Q' to access Manager's payroll\n");
printf("-----------------------------------------------\n");
choiceInput();
}
float managerIntro()
{
float managerTotal;
char charReturn = 0;
printf("-----------------------------------------------\n");
printf("You have selected 'Manager's payroll'\n");
printf("-----------------------------------------------\n");
printf("Please enter your fixed weekly salary: $");
scanf("%f", &managerTotal);
printf("-----------------------------------------------\n");
printf("You have entered $%.2f as the weekly fixed salary\n", managerTotal);
printf("-----------------------------------------------\n");
printf("Press 'R' to return back to the main menu\n\n");
scanf(" %c", &charReturn); // space before %c to tell scanf to skip the leading whitespace
switch (charReturn)
{
case 'r':
choosePayroll();
default:
printf("You have entered an invalid key, press any key to try again\n");
getchar();
getchar();
hourlyIntro();
}
return managerTotal;
}
float hourlyIntro()
{
char charReturn = 0;
float hourlyWage = 0;
float hoursWorked = 0;
float overTimeHours = 0;
float normalPay = 0;
float overTimePay = 0;
float hourlyTotal;
printf("-----------------------------------------------\n");
printf("You have selected 'Hourly worker's payroll'\n");
printf("-----------------------------------------------\n");
printf("Please enter the hourly wage for the worker: $");
scanf("%f", &hourlyWage);
printf("-----------------------------------------------\n");
printf("You have entered $%.2f as the hourly wage.", hourlyWage);
printf("\n-----------------------------------------------");
printf("\nPlease enter how many hours the worker has worked this week: ");
scanf("%f", &hoursWorked);
printf("\n-----------------------------------------------");
if (hoursWorked > 40) {
overTimeHours = hoursWorked - 40;
hoursWorked = 40;
}
normalPay = hourlyWage * hoursWorked;
overTimePay = (hourlyWage * 1.5) * overTimeHours;
hourlyTotal = normalPay + overTimeHours;
printf("\nNormal weekly pay : $%.2f\nOvertime weekly pay: $%.2f\n\nTotal weekly pay: $%.2f\n\n", normalPay, overTimePay, hourlyTotal);
printf("Press 'R' to return back to the main menu\n");
scanf(" %c", &charReturn); // space before %c to tell scanf to skip the leading whitespace
switch (charReturn)
{
case 'r':
choosePayroll();
default:
printf("You have entered an invalid key, press any key to try again\n");
getchar();
getchar();
hourlyIntro();
}
return hourlyTotal;
}
float commissionIntro() {
char charReturn = 0;
float basicSalary = 250;
float itemAPrice = 0;
float itemBPrice = 0;
float itemCPrice = 0;
float itemAQuantity = 0;
float itemBQuantity = 0;
float itemCQuantity = 0;
float itemACommission = 0;
float itemBCommission = 0;
float itemCCommission = 0;
float totalCommission = 0;
float commissionTotal = 0;
printf("-----------------------------------------------\n");
printf("You have selected 'Commission worker's payroll'\n");
printf("-----------------------------------------------\n");
printf("Please enter the price of Item A: $");
scanf("%f", &itemAPrice);
printf("-----------------------------------------------\n");
printf("Please enter the quantity of Item A sold this week: ");
scanf("%f", &itemAQuantity);
printf("-----------------------------------------------\n");
printf("Please enter the price of Item B: $");
scanf("%f", &itemBPrice);
printf("-----------------------------------------------\n");
printf("Please enter the quantity of Item B sold this week: ");
scanf("%f", &itemBQuantity);
printf("-----------------------------------------------\n");
printf("Please enter the price of Item C: $");
scanf("%f", &itemCPrice);
printf("-----------------------------------------------\n");
printf("Please enter the quantity of Item C sold this week: ");
scanf("%f", &itemCQuantity);
printf("\n-----------------------------------------------\n");
itemACommission = itemAQuantity * (itemAPrice * 0.057);
itemBCommission = itemBQuantity * (itemBPrice * 0.064);
itemCCommission = itemCQuantity * (itemCPrice * 0.072);
totalCommission = itemACommission + itemBCommission + itemCCommission;
commissionTotal = totalCommission + basicSalary;
printf("Commission for item A: $%.2f\n", itemACommission);
printf("Commission for item B: $%.2f\n", itemBCommission);
printf("Commission for item C: $%.2f\n", itemCCommission);
printf("Total commission: $%.2f\n", totalCommission);
printf("Total pay: $%.2f\n", commissionTotal);
printf("-----------------------------------------------\n");
printf("Press 'R' to return back to the main menu\n\n");;
scanf(" %c", &charReturn); // space before %c to tell scanf to skip the leading whitespace
switch (charReturn)
{
case 'r':
choosePayroll();
default:
printf("You have entered an invalid key, press any key to try again\n");
getchar();
getchar();
hourlyIntro();
}
return commissionTotal;
}
float pieceworkerIntro() {
char charReturn;
float quantityItem1;
float quantityItem2;
float quantityItem3;
float priceItem1 = 22.50;
float priceItem2 = 24.50;
float priceItem3 = 26;
float payItem1;
float payItem2;
float payItem3;
float pieceworkerTotal;
printf("-----------------------------------------------\n");
printf("You have selected 'Pieceworker's payroll'\n");
printf("-----------------------------------------------\n");
printf("Please enter the quantity of Item 1 produced this week: ");
scanf("%f", &quantityItem1);
printf("-----------------------------------------------\n");
printf("Please enter the quantity of Item 2 produced this week: ");
scanf("%f", &quantityItem2);
printf("-----------------------------------------------\n");
printf("Please enter the quantity of Item 3 produced this week: ");
scanf("%f", &quantityItem3);
printf("-----------------------------------------------\n");
payItem1 = quantityItem1 * priceItem1;
payItem2 = quantityItem2 * priceItem2;
payItem3 = quantityItem3 * priceItem3;
pieceworkerTotal = payItem1 + payItem2 + payItem3;
printf("\nItem 1 pay: $%.2f\nItem 2 pay: $%.2f\nItem 3 pay: $%.2f\n\nTotal pay: $%.2f", payItem1, payItem2, payItem3);
printf("Press 'R' to return back to the main menu\n\n");
scanf(" %c", &charReturn); // space before %c to tell scanf to skip the leading whitespace
switch (charReturn)
{
case 'r':
choosePayroll();
default:
printf("You have entered an invalid key, press any key to try again\n");
getchar();
getchar();
hourlyIntro();
}
}
float choiceInput()
{
char userChoice;
float managerTotal;
float hourlyTotal;
float commissionTotal;
float pieceworkerTotal;
scanf(" %c", &userChoice);
do {
switch (userChoice) {
case '1':
managerTotal = managerIntro();
break;
case '2':
hourlyTotal = hourlyIntro();
break;
case '3':
commissionTotal = commissionIntro();
break;
case '4':
pieceworkerTotal = pieceworkerIntro();
break;
case 'q':
printf("Manager total is: $%.2f", managerTotal);
printf("Hourly total is: $%.2f", hourlyTotal);
printf("Commission total is: $%.2f", commissionTotal);
printf("Pieceworker total is: $%.2f", pieceworkerTotal);
return 0;
default:
printf("You have entered an invalid key, please try again\n");
getchar();
getchar();
choosePayroll();
break;
}
} while (userChoice != 'Q');
}
The function converterm(met, bri); when called is not returning proper values. The code is still incomplete but it works for some options. Just type-in the values and whenever asked which option to select, select option 1 and see the results.
At this line conm.m = conb.ft / 3.2808; it do not return expected values.
//METRIC_BRITISH - BUILD 1.0
#include<stdio.h>
#include<stdlib.h>
#include<process.h>
//GLOBAL-STRUCTURES DECLARATION
struct metric
{
float m;
float cm;
};
struct british
{
float ft;
float in;
};
//GLOBAL-STRUCTURE-VARIABLE DECLARATION
struct metric met = { 0,0 };
struct british bri = { 0,0 };
int q = 0;
int w = 0;
//USER-DEFINED FUNCTION
struct metric converterm(struct metric conm, struct british conb);
struct british converterb(struct british conb, struct metric conm);
void header();
void header()
{
printf("*-*-*-*-*METRIC_BRITISH*-*-*-*-*");
printf("\n\n");
}
//PROGRAM STARTS HERE
main()
{
//VARIABLE-DECLARATION
int n = 0, c = 0, b = 0, v = 0, i = 0;
//FUNCTION CALL-OUT
header();
printf("Format : Metric \n\n");
printf("Enter the Value for Metres : ");
scanf_s("%f", &met.m);
printf("\n");
printf("Enter the Value for Centimetres : ");
scanf_s("%f", &met.cm);
printf("\n");
printf("*--------------------------------------------*\n\n");
printf("Format : British \n\n");
printf("Enter the Value for Feet : ");
scanf_s("%f", &bri.ft);
printf("\n");
printf("Enter the Value for Inches : ");
scanf_s("%f", &bri.in);
printf("\n\n");
printf("In which Format would you like to add other value? \n");
printf("1. Metric \n");
printf("2. British \n");
printf("Enter any Option : ");
while (i == 0)
{
printf("\n");
scanf_s("%d", &n);
switch (n)
{
case 1:
printf("In which Unit you want to add value? \n");
printf("1. Metres \n");
printf("2. Centimetres \n");
printf("Enter any Option : ");
scanf_s("%d", &c);
q = c;
met = converterm(met, bri);
i = 1;
break;
case 2:
printf("In which Unit you want to add value? \n");
printf("1. Feet \n");
printf("2. Inch \n");
printf("Enter any Option : ");
scanf_s("%d", &c);
q = c;
bri = converterb(bri, met);
i = 1;
break;
default:
printf("INVALID OPTION. \n");
printf("Please Enter Correct Option.");
i = 0;
break;
}
}
printf("Values for Metric : \n");
printf("Metres = %d \n", met.m);
printf("Centimetre = %d \n", met.cm);
printf("\n*--------------------------------------------*\n\n");
printf("Values for British : \n");
printf("Feet = %d \n", bri.ft);
printf("Inch = %d \n", bri.in);
//TERMINAL-PAUSE
system("pause");
}
struct metric converterm(struct metric conm, struct british conb)
{
int i = 0;
switch (q)
{
case 1:
printf("\n");
printf("Would you like to Add? \n");
printf("1. Add Feet to Metre \n");
printf("2. Add Inch to Metre \n");
printf("Enter any Option : ");
scanf_s("%d", &i);
break;
case 2:
printf("\n");
printf("Would you like to Add? \n");
printf("1. Add Feet to Centimetre \n");
printf("2. Add Inch to Centimetre \n");
printf("Enter any Option : ");
scanf_s("%d", &i);
break;
}
if (i == 1)
{
conm.m = conb.ft / 3.2808;
//conm.m = conb.in / 39.370;
}
else
{
conm.cm = conb.ft / 0.032808;
//conm.cm = conb.in / 0.39370;
}
return(conm);
}
struct british converterb(struct british conb, struct metric conm)
{
int i = 0;
switch (w)
{
case 1:
printf("\n");
printf("Would you like to Add? \n");
printf("1. Add Metre to Feet \n");
printf("2. Add Centimetre to Feet \n");
printf("Enter any Option : ");
scanf_s("%d", &i);
break;
case 2:
printf("\n");
printf("Would you like to Add? \n");
printf("1. Add Metre to Inch \n");
printf("2. Add Centimetre to Inch \n");
printf("Enter any Option : ");
scanf_s("%d", &i);
break;
}
if (i == 1)
{
conb.ft = conm.m*3.2808;
//conb.ft = conm.cm*0.032808;
}
else
{
conb.in = conm.m*39.370;
//conb.in = conm.cm*0.39370;
}
return(conb);
}
The problem is in the part where you try to print out the values. In case of
printf("Metres = %d \n", met.m);
printf("Centimetre = %d \n", met.cm);
and
printf("Feet = %d \n", bri.ft);
printf("Inch = %d \n", bri.in);
You're using %d format specifier to print the value of the variables of float types. You should be using %f instead.
FWIW, using inappropriate type of argument for a format specifier invokes undefined behavior.
This question already has answers here:
Parsing input with scanf in C
(5 answers)
The program doesn't stop on scanf("%c", &ch) line, why? [duplicate]
(2 answers)
Closed 7 years ago.
Here is the code...
#include <stdio.h>
int main(void) {
//identifiy variables
float grade, total;
total = 0;
char type;
//prompt user for type of assignment
printf("Please enter the type of Assignment: ");
scanf("%c", &type);
//prompt user for grade
printf("Please enter grade:(##.#) ");
scanf("%f", &grade);
//while grade>=0
while (grade>=0) {
//if Homework
if (type == 'H') {
//calculate grade
grade = grade * 0.3;
//calculate total
total = grade + total;
//prompt user for type of assignment
printf("Please enter the type of Assignment: ");
scanf("%c", &type);
//ask for new grade
printf("\nPlease enter grade: ");
scanf("%f", &grade);
}
//if Lab
else if (type == 'L') {
//calculate grade
grade = grade* 0.15;
//calculate total
total = grade + total;
//prompt user for type of assignment
printf("Please enter the type of Assignment: ");
scanf("%c", &type);
//ask for new grade
printf("\nPlease enter grade: ");
scanf("%f", &grade);
}
//if Quiz
else if (type == 'Q') {
//calculate grade
grade = grade* 0.2;
//calculate total
total = grade + total;
//prompt user for type of assignment
printf("Please enter the type of Assignment: ");
scanf("%c", &type);
//ask for new grade
printf("Please enter grade: ");
scanf("%f", &grade);
}
//if Exam
else if (type == 'E') {
//calculate grade
grade = grade* 0.2;
//calculate total
total = grade + total;
//prompt user for type of assignment
printf("Please enter the type of Assignment: ");
scanf("%c", &type);
//ask for new grade
printf("\nPlease enter grade: ");
scanf("%f", &grade);
}
//if Final
else {
//calculate grade
grade = grade* 0.15;
//calculate total
total = grade + total;
//prompt user for type of assignment
printf("Please enter the type of Assignment: ");
scanf("%c", &type);
//ask for new grade
printf("\nPlease enter grade: ");
scanf("%f", &grade);
}
}
//print grade total
printf("%f", total);
//check to see the final letter grade
//if total>=90
if (total>=90){
printf(" A");
}
//if total>=80
else if (total>=80) {
printf(" B");
}
//if total>=70
else if (total>=70){
printf(" C");
}
//if total>=60
else if (total>=60){
printf(" D");
}
//else
else{
printf(" F");
}
}
Heres the issue...
The computer allows you to input the assignment type and a grade. Then the computer prints the "Please enter the type of Assignment:" but dose not allow the user to input a type. It just skips straight to asking the user for a grade and allowing a grade input.
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 7 years ago.
Improve this question
I've been trying to solve this error for half an hour now.
How do I get this code to work?
Here's the input, please point out my mistake(s).
#include <stdio.h>
#include <math.h>
void main()
{
const float pi = 3.142;
int choice;
float radius, volume, volts, ohms, watts, mass, accel, force;
printf("\n1. Calculate the volume of a sphere");
printf("\n2. Calculate the power of a circuit");
printf("\n3. Calculate the force of an object");
printf("\n-----------------------------------\n");
printf("What is your choice? : ");
scanf("%d", &choice);
if(choice==1)
printf("Enter value of radius (cm) : ");
scanf("%f", &radius);
volume = 4/3 * pi * pow(radius,3);
printf("Volume of a sphere is %.2f", volume);
else if(choice==2)
printf("Enter value of voltage (volts) : ");
scanf("%f", &volts);
printf("Enter value of resistance (ohms) : ");
scanf("%f", &ohms);
watts = pow(volts,2) / ohms;
printf("Power of circuit is : %.2f watts", watts);
else if(choice==3)
printf("Enter mass of object (kg) : ");
scanf("%f", &mass);
printf("Enter acceleration (meters per second squared) : ");
scanf("%f", &accel);
force = mass * accel;
printf("The force of the object is : %.2f Neutons", force);
else
printf("You've entered an invalid choice...");
getch();
}
Use braces if a if/else block has multiple lines:
if (choice==1) {
printf("Enter value of radius (cm) : ");
scanf("%f", &radius);
volume = 4/3 * pi * pow(radius,3);
printf("Volume of a sphere is %.2f", volume);
} else if (choice==2) {
printf("Enter value of voltage (volts) : ");
scanf("%f", &volts);
printf("Enter value of resistance (ohms) : ");
scanf("%f", &ohms);
watts = pow(volts,2) / ohms;
printf("Power of circuit is : %.2f watts", watts);
} else if (choice==3) {
printf("Enter mass of object (kg) : ");
scanf("%f", &mass);
printf("Enter acceleration (meters per second squared) : ");
scanf("%f", &accel);
force = mass * accel;
printf("The force of the object is : %.2f Neutons", force);
} else printf("You've entered an invalid choice...");
Without braces your code is interpreted like
// Standalone if block
if (choice==1)
printf("Enter value of radius (cm) : ");
// End of the if block
// ...
// else without previous if (syntax error)
else if (choice==2)
printf("Enter value of voltage (volts) : ");
Use if..else if..else block properly with braces.
If you are using GCC compiler then use following code and compile code with math library.
For example (correct way): gcc test.c -lm
otherwise it gives error : undefined reference to 'pow' (math library function)
#include <stdio.h> //Standard IO functions
#include <math.h> //math functions
int main()
{
const float pi = 3.142;
int choice;
float radius, volume, volts, ohms, watts, mass, accel, force;
printf("\n1. Calculate the volume of a sphere");
printf("\n2. Calculate the power of a circuit");
printf("\n3. Calculate the force of an object");
printf("\n-----------------------------------\n");
printf("What is your choice? : ");
scanf("%d", &choice);
if(choice==1)
{
printf("Enter value of radius (cm) : ");
scanf("%f", &radius);
volume = 4/3 * pi * pow(radius,3);
printf("Volume of a sphere is %.2f", volume);
}
else if(choice==2)
{
printf("Enter value of voltage (volts) : ");
scanf("%f", &volts);
printf("Enter value of resistance (ohms) : ");
scanf("%f", &ohms);
watts = pow(volts,2) / ohms;
printf("Power of circuit is : %.2f watts", watts);
}
else if(choice==3)
{
printf("Enter mass of object (kg) : ");
scanf("%f", &mass);
printf("Enter acceleration (meters per second squared) : ");
scanf("%f", &accel);
force = mass * accel;
printf("The force of the object is : %.2f Neutons", force);
}
else
printf("You've entered an invalid choice...");
return 0;
}
missing brackets in if else command
#include <stdio.h>
void main()
{
const float pi = 3.142;
int choice;
float radius, volume, volts, ohms, watts, mass, accel, force;
printf("\n1. Calculate the volume of a sphere");
printf("\n2. Calculate the power of a circuit");
printf("\n3. Calculate the force of an object");
printf("\n-----------------------------------\n");
printf("What is your choice? : ");
scanf("%d", &choice);
if(choice==1)
{
printf("Enter value of radius (cm) : ");
scanf("%f", &radius);
volume = 4/3 * pi * pow(radius,3);
printf("Volume of a sphere is %.2f", volume);
}
else if(choice==2)
{
printf("Enter value of voltage (volts) : ");
scanf("%f", &volts);
printf("Enter value of resistance (ohms) : ");
scanf("%f", &ohms);
watts = pow(volts,2) / ohms;
printf("Power of circuit is : %.2f watts", watts);
}
else if(choice==3)
{
printf("Enter mass of object (kg) : ");
scanf("%f", &mass);
printf("Enter acceleration (meters per second squared) : ");
scanf("%f", &accel);
force = mass * accel;
printf("The force of the object is : %.2f Neutons", force);
}
else
printf("You've entered an invalid choice...");
getch();
}
You are missing the curly braces {}.
Do: if() { ... } else if() { ...}. You should take a look at: if statement without brackets