I've written a special calculator which prompts the user for 2 numbers then displays a menu which basicly asks the user what to do with that input. It works great however no matter what numbers I input the result is 0. What am I doing wrong?
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
#include <math.h>
int main()
{
char a, rad, patrat;
float x, y, media, radical, pat1, pat2;
patrat = 253;
rad = 251;
loop:
printf("Input 2 numbers...\n");
scanf("%f %f", &x, &y);
media = (x+y)/2;
radical = sqrt(x+y);
pat1 = x*x;
pat2 = y*y;
loop2:
printf("\n \nA - Arithmetic media.\n");
printf("B - Square root.\n");
printf("C - Sqare of the 2 numbers.\n");
printf("D - Write other numbers.\n");
printf("E - Terminate the program.\n");
a = getch();
switch(a) {
case'a':
system("cls");
printf("Media of the 2 numbers is %f", &media);
goto loop2;
case'b':
system("cls");
printf("%c%f + %f = %f", &rad, &x, &y, &radical);
goto loop2;
case'c':
system("cls");
printf("%f%c = %f, %f%c = %f", &x, &patrat, &pat1, &y, &patrat, &pat2);
goto loop2;
case'd':
goto loop;
case'e':
return 0;
}
}
You're using & in your printf statements, you shouldn't be. Scanf has it as it's writing so takes pointers.
Why are you using the operator & to your printf arguments?
printf doesn't take pointer arguments for %f conversion specification
float b;
scanf("%f", &b);
but
float a = 42;
printf("%f\n", a);
printf("Media of the 2 numbers is %f", &media);
should be
printf("Media of the 2 numbers is %f", media);
similarly for all other printf()
Generally goto statements are considered harmful when they are called backwards! So please avoid them. The same functionality can be done by a while(1) for for(;;) loop with proper termination condition.
In your printf statement, you are using
printf("Media of the 2 numbers is %f", &media);
&media is the address of your variable media.
In scanf, we provide the address of the variable as parameter so that it stores the values at that address. But in printf, we provide the variable value and not the variable address. If you provide variable address then it would print the address and not the value.
So the correction should be
printf("Media of the 2 numbers is %f", media);
Related
I am getting an infinite loop for the program shown below when I run it twice without giving input for the first time. But when I give input on the first run then it is working perfectly.
But if I run it once and don't give input and rerun it, it results in an infinite loop.
How can I resolve the issue?
I am using VS Code.
Source code:
/* UNIT CONVERSION
kms to miles
inches to foot
cms to inches
pound to kgs
inches to meters
*/
#include <stdio.h>
int main(int argc, char const *argv[])
{
int x;
float a;
start:
printf("\nSelect the type of unit conversion you want\nkms to miles\tPRESS 1\ninches to foot\tPRESS 2\ncms to inches\tPRESS 3\npound to kgs\tPRESS 4\ninches to meters\tPRESS 5\nPRESS 0 TO EXIT\n");
scanf("%d", &x);
switch (x)
{
case 0:
goto end;
case 1:
printf("Enter the value in Km to be converted into miles\n");
scanf("%f", &a);
printf("%f kms is %f miles\n", a, 0.621371 * a);
goto start;
case 2:
printf("Enter the value in inches to be converted to foot\n");
scanf("%f", &a);
printf("%f inches is %f feet\n", a, 0.0833333 * a);
goto start;
case 3:
printf("Enter the value in cms to be converted to inches\n");
scanf("%f", &a);
printf("%f cms is %f inches\n", a, a * 0.393701);
goto start;
case 4:
printf("Enter the value in pound to be converted to kgs\n");
scanf("%f", &a);
printf("%f pound(s) is equal to %f kgs", a, a * 0.453592);
goto start;
case 5:
printf("Enter the value in inches to be converted to metres\n");
scanf("%f", &a);
printf("%f inch(es) is equal to %f metre(s)", a, a * 0.0254);
goto start;
default:
printf("You have not entered a valid input :(\n");
goto start;
}
end:
printf("You have successfully exited the program\n");
return 0;
}
If you don't give any input, by which you probably mean you just hit enter, scanf fails and the x variable will not be set.
if (scanf("%d", &x) != 1) {
x = -1;
}
This will set x to an invalid value in case no number was given. The code checks that scanf actually made exactly 1 conversion.
Always check scanf made the number of conversions requested.
And stop using goto. Use proper while, for, or do while loops.
Im making a calculator with A LOT of functions, Im not nearly done with the functions. But I thought, I want the program active after returning me the value I asked for. My logic was to put it into a while loop, but clearly my idea and how I put it are not equal. Or maybe my logic doesnt work in this case. Anyway, imagine I ask the program how much its 2+2 and it returns me 4. Done, but I want it to ask me again for another operation, how can I do that?
Im really new with this stuff, so thanks for the help.
To resume the code below. I ask for a value, then scan it, then ask for a operator, then I ask wether if the user want to continue or not, if he says yes thats the condition for the loop ---> while(condition != 'yes' );{
And if not, just end the program. And I putted the operations inside the loop.
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int main()
{
int input;
double sinus;
int op;
printf(" What function do you want to use? \n \n --------------------------------------- \n");
printf(" BASIC OPERATIONS --> type 1 \n --------------------------------------- \n");
printf(" TRIGONOMETRIC FUNCTIONS \n sin --> type 2 \n cos --> type 3 \n tan --> type 4 \n arcsin --> type 5 \n arccos --> type 6 \n arctan --> type 7 \n --------------------------------------- \n");
scanf("%d", &op);
char condition[5];
printf("Stop? Type: yes or no");
scanf("%s", &condition);
while(condition != 'yes' );{
if (op == 1) {
double val1;
char op1;
double val2;
printf("Please type a number: \n" );
scanf("%lf", &val1);
printf("Please type an operator: \n" );
scanf(" %c", &op1);
printf("Please type another number: \n" );
scanf("%lf", &val2);
if (op1 == '+') {
printf("%f \n", val1 + val2);
}
if (op1 == '-') {
printf("%f \n", val1 - val2);
}
if (op1 == '*') {
printf("%f \n", val1 * val2);
}
if (op1 == '/') {
printf("%f \n", val1 / val2);
}
}
else if (op == 2) {
double arg;
printf("Please type the argument of sin(x) \n");
scanf("%lf", &arg);
printf("The value is %f", sin(arg));
}
else if (op == 3) {
double arg;
printf("Please type the argument of cos(x) \n");
scanf("%lf", &arg);
printf("The value is %f", cos(arg));
}
else if (op == 4) {
double arg;
printf("Please type the argument of tan(x) \n");
scanf("%lf", &arg);
printf("The value is %f", tan(arg));
}
else if (op == 5) {
double arg;
printf("Please type the argument of arcsin(x) \n");
scanf("%lf", &arg);
printf("The value is %f", asin(arg));
}
else if (op == 6) {
double arg;
printf("Please type the argument of arccos(x) \n");
scanf("%lf", &arg);
printf("The value is %f", acos(arg));
}
else if (op == 7) {
double arg;
printf("Please type the argument of arctan(x) \n");
scanf("%lf", &arg);
printf("The value is %f", atan(arg));
}
else {
printf("%d", 0);
}
}
}
Sorry for too many to read:((( Im not experienced with forums.
The following example will give you an idea how things can be repeated based on input.
check how strcmp is done,that way you are doing is wrong.
Also consider using switch for handling multiple cases of input and their operations.
#include<stdio.h>
#include <string.h>
#include <ctype.h> // isspace
int main() {
char choice[] = "Yes";
do{
int i = 0;
/**
* implement all you want here
*/
printf("Enter Yes to repeat, to exit enter any other non blank string\n");
while(isspace(choice[i] = getchar()));
while((choice[++i] = getchar()) != '\n');
choice[i] = '\0';
printf("choice = %s, i = %d\n", choice, i);
}while(!strcmp(choice,"Yes") );
return 0;
}
The program below is supposed to demonstrate using an array of pointers to functions. Everything works great, except the scanf statements that change the value of num1 and num2 (I have them commented in the code). If I initialize the variables and have them equaling, say, 2, then when I run the program their value's will be 2 regardless of what I enter in scanf to replace the value. Any help with this would be greatly appreciated!
#include <stdio.h>
// function prototypes
void add (double, double);
void subtract (double, double);
void multiply (double, double);
void divide (double, double);
int main(void)
{
// initialize array of 4 pointers to functions that each take two
// double arguments and return void.
void(*f[4])(double, double) = { add, subtract, multiply, divide };
double num1; // variable to hold the 1st number
double num2; // variable to hold the 2nd number
size_t choice; // variable to hold the user's choice
printf("%s", "Which operation would you like to perform on the two numbers?\n");
printf("%s", "[0] add\n");
printf("%s", "[1] subtract\n");
printf("%s", "[2] multiply\n");
printf("%s", "[3] divide\n");
printf("%s", "[4] quit\n");
scanf_s("%u", &choice);
// process user's choice
while (choice >= 0 && choice < 4)
{
printf("%s", "Enter a number: ");
scanf_s("%f", &num1); // <--- THIS SCANF_S STATEMENT ISN'T CHANGING NUM1'S VALUE
printf("%s", "Enter another number: ");
scanf_s("%f", &num2); // <--- THIS SCANF_S STATEMENT ISN'T CHANGING NUM2'S VALUE
// invoke function at location choice in array f and pass
// num1 and num2 as arguments
(*f[choice])(num1, num2);
printf("%s", "Which operation would you like to perform on the two numbers?\n");
printf("%s", "[0] add\n");
printf("%s", "[1] subtract\n");
printf("%s", "[2] multiply\n");
printf("%s", "[3] divide\n");
printf("%s", "[4] quit\n");
scanf_s("%u", &choice);
} // end while loop
puts("Program execution completed");
} // end main
void add(double a, double b)
{
printf("%1.2f + %1.2f = %1.2f\n", a, b, a + b);
}
void subtract(double a, double b)
{
printf("%1.2f - %1.2f = %1.2f\n", a, b, a - b);
}
void multiply(double a, double b)
{
printf("%1.2f * %1.2f = %1.2f\n", a, b, a * b);
}
void divide(double a, double b)
{
printf("%1.2f / %1.2f = %1.2f\n", a, b, a / b);
}
As others have said, use the correct format specifiers.
1) When using scanf(), "%f" is for float and "%lf" is for double.
double num1;
// scanf_s("%f", &num1);
scanf_s("%lf", &num1);
2) The use of "%u" may work given your platform, but size_t and unsigned are not necessarily the same size. With C11, (and maybe C99) use the z modifier.
size_t choice;
// scanf_s("%u", &choice);
scanf_s("%zu", &choice);
3) It is always good to check the result from scanf_s().
if (1 != scanf_s(...)) {
; // handle_error();
}
Sorry for not adding the whole code. Dumb mistake on my part.
#include <stdio.h>
int main(int argc, char ** argv) {
float celcius, fahrenheit, kelvin, interval;
int c, f, k;
char temp;
printf("which temperature is being input? (C,F,K) ");
scanf("%s", &temp);
if(temp == 'c') {
printf("enter a starting temperature");
scanf("%f", &celcius);
fahrenheit=celcius*9/5+32;
kelvin=celcius+273.2;
printf("%f, %f, %f", celcius, fahrenheit, kelvin);
}
else if(temp == 'f') {
printf("Please enter a starting temperature");
scanf("%f", &fahrenheit);
celcius=fahrenheit-32*5/9;
kelvin=fahrenheit-32*5/9+273.2;
printf("%f, %f, %f", celcius, fahrenheit, kelvin);
}
else if(temp == 'k') {
printf("enter a starting temperature");
scanf("%f", &kelvin);
fahrenheit=kelvin-273*1.8+32;
celcius=kelvin-273.2;
printf("%f, %f, %f", celcius, fahrenheit, kelvin);
}
}
So it asks for what temperature is being input and the starting temperature but why isn't it calculating the math equation?
It is calculating the math equations
fahrenheit=celcius*9/5+32;
kelvin=celcius+273.15;
but you are not printing it.
Try this
printf("%f, %f, %f", celcius, fahrenheit, kelvin);
And do not forget to change scanf("%s", &temp); to
scanf(" %c", &temp);
temp = tolower(temp); // include <ctype.h> header
or better to place
int c;
while ((c = getchar()) != `\n` && c != EOF);
after scanf(" %c", &temp);. This will eat up all the character other than the first character of the input.
As per OP's comment;
How can I do it so that the Temperature name appears on top of the temperature?
printf("celcius \tfahrenheit \tkelvin);
printf("%5f\t%5f\t%5f", celcius, fahrenheit, kelvin);
Looks like it is calculating, but you're printing the wrong variables. Try replacing c, f, and k with celsius, fahrenheit, and kelvin in the print statement.
You have to be consistent in your variable names, you can't mix them up like you are.
Because you are calculating it like so:
fahrenheit=celcius*9/5+32;
kelvin=celcius+273.15;
However this line is not printing it out, since you have the wrong variables:
printf("%f, %f, %f", c, f, k);
Change that to the proper variable name and type like so:
printf("%f, %f, %f", celcius, fahrenheit, kelvin);
You did not show how you defined your variable temp, but it is extremely dangerous to read a string in this way. If temp is a character, then pointing to the address of it and treating it as a string is asking for trouble. For sure you will have a '\0' written to the location right after temp, and if the user inputs more than a single character the damage they could do is even larger.
You can read a single character with a getc call:
temp = getc(stdin);
I would recommend that you make sure it is lower case - since you are comparing with c:
temp = lower(getc(stdin));
Then obviously, when you print out a variable, you must print out the one you computed. You compute celcius, etc - but your print statement is
printf("%f, %f, %f", c, f, k);
c, f, and k may be valid variables - but they are not the ones you computed in the lines before. Replace the print statement with
printf("Celsius: %.1f; Fahrenheit: %.1f; Kelvin: %.1f\n", celcius, fahrenheit, kelvin);
Or, if you want the name above the number:
printf("\tC\tF\tK\n\t%6.1f\t%6.1f\t%6.1f\n", celcius, fahrenheit, kelvin);
Note the use of \t - the tab character - to get things to align (approximately) and the format specifier %4.1f to say "number in a field width of 6, with one significant digit after the decimal".
One more note - it's Celsius, not celcius. But that is the least of your problems.
Write a program that requests two floating-point numbers and prints the value of their difference divided by their product. Have the program loop through pairs of input values until the user enters nonnumeric input.
Use a function to return the value of the calculation.
I've successfully completed this exercise without using function but can't get it right using function. The program itself runs but doesn't return any value in fact it crashes.
Please any help would be appreciated.
Here is my program:
#include <stdio.h>
#include <string.h>
double result (double x, double y);
int main(void)
{
double num1, num2, res;
printf("This while calculate difference of two numbers by their product.\n");
printf("Enter first number followed by second number\n");
while (scanf("%lf %lf", &num1, &num2 ==2))
{
res= result(num1, num2);
printf("the result is equal to %.3g\n", res);
printf("Enter next set of numbers or q to quit\n");
}
return 0;
}
double result(double x, double y)
{
double output;
output = (y-x)/(x*y);
return output;
}
while (scanf("%lf %lf", &num1, &num2 ==2))
was meant to be:
while (scanf("%lf %lf", &num1, &num2) ==2)
Try changing
while (scanf("%lf %lf", &num1, &num2 ==2))
to
while (scanf("%lf %lf", &num1, &num2) ==2)