Switching between data types - c

I'm attempting to create a simple calculator in C. For the calculator, I'm trying to include an option to switch between using double precision variables and integers. By default the calculator is in double precision mode.
Is there a way to easily toggle my data types back and forth between int and double? Preferably through type casting?
For example, here's the addition part of switch statement (the first case):
case 1:
printf("Enter first term: ");
scanf("%lf", &a);
printf("Enter second term: ");
scanf("%lf", &b);
printf("The sum is: %.15lf\n", a + b);
break;
The cases for subtracting, multiplying, and dividing follow the same format; respectively, cases 2, 3, and 4. Is there a way to apply a case (say add a case 5) to switch all double values to int?

Rather than trying to change the values, just output the result as an int:
printf("The sum is: %d\n", (int)(a + b));

Related

I don't understand how to use printf correctly in this circumstance

This is code for an assignment in class currently, the question asks us to prompt the user for a number to find the lowest positive divisor for.
I keep getting the error:
warning: format not a string literal and no format arguments [-Wformat-security]
while using this code
#include <stdio.h>
int main(void)
{
int divisor;
int dividend;
divisor=2;
printf("Enter a number to divide: ");
scanf("%d", &dividend);
while(divisor!=0)
{
divisor++;
}
printf("%s","The lowest positive divisor is: ",dividend);
}
I think i need to be using %s somewhere but I am new to c++ and don't quite understand what formatting changes should be made
printf("%s","The lowest positive divisor is: ",dividend);
You only have one format specifier specified in your string but you pass 2 variables to printf. You should specify the dividend specifier too:
printf("%s %d","The lowest positive divisor is: ",dividend);
Place the %s inline like:
printf("The lowest positive divisor is: %s", dividend);
But in this case use %d because it's an integer:
printf("The lowest positive divisor is: %d", dividend);

why calculator I made not working? [duplicate]

This question already has answers here:
Is floating point math broken?
(31 answers)
Closed 4 years ago.
what i coded is
#include <stdio.h>
int main(){
float a, b;
printf("enter initial value.");
fflush(stdout);
scanf("%f", &a);
printf("add up the following number.");
fflush(stdout);
scanf("%f", &b);
printf("current value is %f.\n", (a+b));
fflush(stdout);
b = a+b;
printf("enter a value to subtract.");
fflush(stdout);
scanf("%f", &a);
printf("current value is %f. \n", b-a);
fflush(stdout);
b = b-a;
printf("enter a value to multiply.");
fflush(stdout);
scanf("%f", &a);
printf("current value is %f. \n", a*b);
fflush(stdout);
b = a*b;
printf("enter a value to devide.");
fflush(stdout);
scanf("%f", &a);
printf("current value is %f. \n", b/a);
fflush(stdout);
return 0;
}
Output:
enter initial value. 1000000
add up the following number. 9000000
current value is 10000000.000000.
enter a value to subtract. 0
current value is 10000000.000000.
enter a value to multiply. 1000000
current value is 10000000000000.000000.
enter a value to devide. 10
current value is 999999982796.800050.
https://i.stack.imgur.com/xuqab.png
i want 1000000000000.000000 as a result but 999999982796.800050 is all i've got....
what should i fix?
Single precision float can represent any real number for 6 decimal digits of precision. 999999982796.800050 meets that criteria.
This specific example may be fixed simply by using double, which is good for 15 decimal digits of precision.
If you must handle math with arbitrary precision for very large numbers, instead of using a float or double, look into an arbitrary precision library. A common on is called GMP
The idea behind an arbitrary precision library is the same as the idea behind how we do math as humans. A single "digit" can only store 10 possible values, but by creating an array of digits we can generate indiscriminately large values without losing accuracy.
Libraries like this utilize arrays and perform math one digit at a time in order to maintain perfect accuracy. They run a lot slower than floats or doubles, but if you care more about precision than speed then it's definitely the way to go.

How to divide 2 int in c?

wanna divide 2 numbers and get the result like this:
5 / 2 = 2.50
But it only outputs 2.
I don't now what i'm doing wrong.
Here my code:
int a;
int b;
int c;
printf("First num\n");
scanf("%d", &a);
printf("Second num\n");
scanf("%d", &b);
c = a / b;
printf("%d", c);
You need a double variable to store the result. int stores only integers. Additionally, you have to typecast the other variables also before performing the division.
Do something like this
double c;
.
.
.
c = (double)a / (double)b;
printf("%f", c);
NOTE:
You do not need the & in printf() statements.
To avoid the typecast in float you can directly use scanf with %f flag.
float a;
float b;
float c;
printf("First number\n");
scanf("%f", &a);
printf("Second number\n");
scanf("%f", &b);
c = a / b;
printf("%f", c);
The '/' - sign is for division. Whenever in C language, you divide an integer with an integer and store the data in an integer, the answer as output is an integer. For example
int a = 3, b = 2, c = 0;
c = a/b; // That is c = 3/2;
printf("%d", c);
The output received is: 1
The reason is the type of variable you have used, i.e. integer (int)
Whenever an integer is used for storing the output, the result will be stored as integer and not a decimal value.
For storing the decimal results, C language provide float, double, long float and long double.
Whenever you perform an operation and desires an output in decimal, then you can use the above mentioned datatypes for your resultant storage variable. For example
int a = 3, b = 2;
float c = 0.0;
c = (float)a/b; // That is c = 3/2;
printf("%.1f", c);
The output received: 1.5
So, I think this will help you to understand the concept.
Remember: When you are using float then the access specifier is %f. You need to convert your answer into float, just as I did, and then the answer will be reflected.
You have to use float or double variables, not int (integer) ones. Also note that a division between two integers will lead to an integer result, meanwhile a division between a float/double and an integer will lead to a float result. That's because C implicitly promote this integer to float.
For example:
5/2 = 2
5/2.0f = 2.5f
Note the .0f, this actually means that we are dividing with a float.
In C, only an int type number is displayed. 5/2 gives a floating point type number. So, the compiler compiles it only with the integer value.

Larger numbers in calculator in C

I have written a calculator in C language and everything works well except for when I try to multiply 99999999*99999999 [eight nines by eight nines]. It automatically rounds them to 100 000 000.0 and obviously, I don't want that to happen. I'm using float for numbers and precision up to .1. I tried changing float to double, but it won't work anyway. I have heard something about %g, yet I have found no information about it and I'm not sure how to make it work. Any help is highly appreciated!
EDIT
this is my code:
#include<stdio.h>
#include<math.h>
int main()
{
char op;
float numberone,numbertwo;
printf("Enter the operation: ");
scanf("%f%c%f\n", &numberone, &op, &numbertwo);
switch(op) {
case '+':
printf("%.1f + %.1f = %.1f",numberone, numbertwo, numberone+numbertwo);
break;
case '-':
printf("%.1f - %.1f = %.1f",numberone, numbertwo, numberone-numbertwo);
break;
case '*':
printf("%.1f * %.1f = %.1f",numberone, numbertwo, numberone*numbertwo);
break;
case '/':
if(numbertwo==0){
printf("You cannot divide by zero.");
}
else{
printf("%.1f / %.1f = %.1f",numberone, numbertwo, numberone/numbertwo);}
break;
case'^':
printf("%f ^ %f = %f", numberone, numbertwo, pow(numberone,numbertwo));
break;
default:
printf("Error! operator is not correct");
break;
}
return 0;
}
and when I multiply 99999999*99999999, the result is : 100 000 000.0*100 000 000.0 = 10 000 000 000 000 000.0.
Your program will work with those values, just use double precision, scanf has to use the %lf format specifier in that case. If you want much bigger values you will have to learn libgmp as mentioned in other answers.
#include <stdio.h>
int main(void)
{
float x, y;
scanf("%f %f", &x, &y);
printf("%f\n", x*y);
return 0;
}
,
$ ./c
99999999 99999999
10000000272564224.000000
Do you mean the value is not exact ? This always happens with floating point numbers. 32 bit floats will be precise only up to ~6 decimal digits, while doubles will be ~15 decimal digits.
http://en.wikipedia.org/wiki/Floating_point#Accuracy_problems
A floating point number (float, double or long double) store numbers as mantissa and exponent (like 3x10^15, for example, but a bit different and in binary). Therefore you are bound to lose some precision bigger than decimals (= different integer if you convert it back) if you store too big integers.
If you want to handle really big numbers, you can use an arbitrary precision arithmetic library like GMP.
You hit the problem of precision inherent to all standard types. They are represented in a defined number of bits. For the integers (char, short, int, long, long long) when you overflow you pass negative (or 0 for unsigned). Ex for char (8 bits) : 126 + 3 gives ... -127
For the floats (float, double, long double) it may be more subtle, because they are represented as a number of bits for the significand part and some other bits for the exponent part (see more details on Wikipedia. In practice single floats can represent numbers as big as 1038, but with no more than 7 or 8 decimal digits in precision.
If you really want to do exact computations with big numbers, you should use multiple precision technics or directly use the excellent gmp library.
As suggested you could use the libgmp if you need to deal with large numbers. Simplified example based on your code:
#include <stdio.h>
#include <stdlib.h>
#include <gmp.h>
int main(void){
char op;
mpz_t x;
mpz_t y;
mpz_t result;
printf("Enter the operation: ");
scanf("%c\n", &op);
char x_str[256];
char y_str[256];
fgets(x_str, sizeof(x_str), stdin);
fgets(y_str, sizeof(y_str), stdin);
mpz_init(x);
mpz_init(y);
mpz_init(result);
mpz_set_str(x, x_str, 10);
mpz_set_str(y, y_str, 10);
switch(op) {
case '+':
mpz_add(result, x, y);
break;
case '*':
mpz_mul(result, x, y);
break;
default:
printf("Error! operator is not correct");
break;
}
gmp_printf("%Zd", x);
printf(" %c ", op);
gmp_printf("%Zd", y);
gmp_printf(" = %Zd\n", result);
mpz_clear(x);
mpz_clear(y);
mpz_clear(result);
return EXIT_SUCCESS;
}
Compile and linkk with the library:
/tmp$ gcc big.c -lgmp -o big
Then run:
/tmp$ ./big
Enter the operation: *
99999999
99999999
99999999 * 99999999 = 9999999800000001

How Can I Convert Float to Int with Modulus in C?

I am so confused with Modulus in C. I am writing a small script that allows the user to input their two number vars, then they can either add, subtract, multiply, divide (easy) or modulus (haven't caught this one yet). What would I be doing wrong in this? I get the "invalid operands to binary %" error, which means I need to format it to an int since it is a float. However what is the best way of doing this with the following? Any C help would be greatly appreciated.
int main (void)
{
float number1, number2, result;
char symbol;
//allow user interaction
printf("Enter your formula: \n");
scanf("%f %c %f", &number1, &symbol, &number2);
switch (symbol) {
case '%':
result = number1 % number2;
printf("Result: %f \n", result);
break;
default:
printf("Operation Error. Program aborted. \n \n");
break;
}
printf("Press any key to continue \n");
getchar();
return 0;
}
Where and how do I convert this?
You can either use a statement like:
result = (int)number1 % (int)number2;
to cast your floats to ints and perform the modulus operation, but you'll lose the decimal precision.
You could also include math.h and use fmod
result = fmod(number1, number2);
I recommend to use the fmod function of the standard C library.
The % operator only works on integer types. To perform the same task with floating points, you'd want to do something like:
#include <math.h>
float modulus(float a, float b)
{
return a - b * floor(a / b);
}
Mod is an integer operation, so it cannot be used on floats. Your case should read something like:
result = (int)number1 % (int)number2;
which will convert both floats to integers, and perform the mod. However, note that you are losing precision by casting a floating point number to an integer, so it is likely the result may not be what you'd expect.
change
case '%':
result = number1 % number2;
to
case '%':
result = (int)number1 % (int)number2;
?
modulo division is for integers. Cast each operand to an integer.

Resources