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.
Related
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));
int num1, num2;
double average;
average=(double)(num1+num2)/2;
printf("average: %d", average);
My test printf shows average as: 0
This is maybe too easy, but I can't see it. My inputs are both "int" and the average is "double" but somehow it is not calculating right ?
You're using the wrong format specifier to printf.
The %d format specifier expects an int argument, but you're passing a double. Using the wrong format specifier invokes undefined behavior.
To print a double, use %f.
printf("average: %f\n", average);
No need to modify the statement average=(double)(num1+num2)/2; to get expected result inside printf use %f instead of %d
1st (num1+num2) is performed, result of this is of integral type. lets say 15. Next when you do (double)15/2 result is of floating type which is 7.500000.
from previous step average = (double)7.500000 average holds 7.500000 but since you printed in %d you are getting 0 as its undefined behavior. instead use %f
Here is the working one
int main() {
int num1 = 7, num2 = 8;
double average;
average = (double)(num1 + num2)/2;
printf("average: %f\n", average);
return 0;
}
int num1, num2;
double average;
average=(num1+num2)/2.; // Using a decimal point forces 2 to be a double.
printf("average: %f\n", average); // Use the correct specifier for double: %f
You should use printf("average= %f",avearge); instead of using "%d" to print the average value.I think it will solve your issues...
Integer division yields an integer result: 1/2 == 0, 5/3 == 1, etc. If you want a floating point result, at least one of the operands must be a floating-point type: 1/2.0f == 0.5f, 5/3.0 == 1.6667, etc.
So, you'll want to divide your sum by 2.0, not 2:
average = (num1 + num2)/2.0;
Secondly, you need to use the %f format specifier for floating-point output:
printf( "average: %f\n", average );
If you want a floating point result, at least one of the operands must be a floating-point type
This is my solution:
average = (num1 + num2)/(double)2;
printf ("Value of 1/2 is: %.4f\n", (double)(1/2));
// Value of 1/2 is: 0.0000
printf ("Value of 1/2 is: %.4f\n", (1/(double)2));
// Value of 1/2 is: 0.5000
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.
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
int main (void)
{
int fahrenheit; // fahrenheit stands for fahrenheit
double c; // c stands for celsius
printf("Enter your fahrenheit, we'll covnvert it into celsius! ");
scanf("%f", &fahrenheit);
c = 5/9 * (fahrenheit - 32);
printf("Here is your %f in celsius!.\n");
return (0);
}
I've followed the code through break points and when it takes in my input the calculations are off, but the formula is correct. Some sort of logic error I can't put my finger on. Please help!
The scanf call uses the wrong format string. You are reading an int so you need it to be:
scanf("%d", &fahrenheit);
The expression 5/9 is evaluated using integer division. In fact the compiler can work it out at compile time. That expression evaluates to 0.
You need to perform floating point division. For instance:
5.0/9
Or:
5/9.0
Or
5.0/9.0
You just need at least one operand to be a floating point value.
Putting this into your expression, you can write:
c = 5.0/9.0 * (fahrenheit - 32);
and obtain the answer that you expect.
Your printf statement is wrong too. You should enable warnings and let the compiler tell you that. You meant to write:
printf("Here is your %f in celsius!.\n", c);
Integer math versus floating point math.
i = 5/9 // i is equal to 0
d = 5.0/9.0 // d is equal to whatever 5 divided by 9 would actually be
You also need to actually print the value:
printf("Here is your %f in celsius!.\n", c);
Short answer: Operations on integers return integers even if the variable you store the result on is a double. Divisions between integers are truncated.
You should write this instead:
c = 5.0/9.0 * (fahrenheit - 32.0);
Adding a ".0" (or even just a ".") to your constant makes them floating point values.