Trying to solve this question I have for HW but I'm stuck with one little problem. I have a series of if statements but the program just skips every if statement even when the condition is met. Ex: User wants to execute 5 - 2, instead of going to the second if statement to check for when the user entered the minus, the program just skips every single if statement.
The question is:
Consider a C program that reads two real numbers from the keyboard
followed by a character where the character can be one of the
operators +, -, *, /, or % providing the addition, subtraction,
multiplication, division, or remainder respectively. Then the result
is displayed on the screen. For example, if the user types:
2.0 3.0 % then your code will display: 2 % 3 = 2 Note: In the above example the inputs are real numbers but the remainder only performs an
integer operation. Hence, the two real numbers must be type cast to
allow computation by remainder. In the case where an invalid operator
is entered (e.g. $) then an error message is printed to the standard
output, e.g. Invalid entry!
My code is:
#include <stdio.h>
int main(void){
double num1, num2, plus, minus, divide, mult, op;
printf("Enter two numbers and an operation you would like to perform on those number: \n");
scanf("%lf %lf %lf", &num1, &num2, &op);
if(op=='+')
{
plus=(num1 + num2);
printf("%lf + %lf = %lf", num1, num2, plus);
}
else if(op=='-')
{
minus=num1-num2;
printf("%lf - %lf = %lf", num1, num2, minus);
}
else if(op=='/')
{
divide=num1/num2;
printf("%lf / %lf = %lf", num1, num2, divide);
}
else if(op=='%')
{
int num1, num2, remain;
remain= (num1%num2);
printf("%d %% %d = %d", num1, num2, remain);
}
else
{
printf("Invalid entry!");
}
return 0;
}
Would really appreciate some help on this, have been struggling for a while on such a small error.
Try putting the line
printf("op=%lf\n",op);
right below your scanf statement to see what value op has for different operations. That solves the mystery of why the if statements were being skipped.
Then, as #l-l suggests, try declaring op as char op;.
#include <stdio.h>
int main(void)
{
double num1, num2, plus, minus, divide, mult, op;
char operation;
printf("Enter first number");
scanf("%lf", &num1);
printf("Enter second number");
scanf("%lf", &num2);
printf("Enter operation");
scanf(" %c", &operation);
if(operation=='+')
{
plus=(num1 + num2);
printf("%lf + %lf = %lf", num1, num2, plus);
}
if(operation=='-')
{
plus=(num1 - num2);
printf("%lf - %lf = %lf", num1, num2, plus);
}
if(operation=='/')
{
plus=(num1 / num2);
printf("%lf / %lf = %lf", num1, num2, plus);
}
if(operation=='*')
{
plus=(num1 * num2);
printf("%lf * %lf = %lf", num1, num2, plus);
}
return 0;
}
Try this. The code compiled and working fine.
Related
I wanted to write a little calculator, which I have already done by using cout and cin, and I used double instead of int to not only get integers as an output.
At school, I then saw that we're going to use printf() and scanf(). To practice the new commands, I wanted to rewrite my program, but when I run my program I only see a lot of zeros after the comma as an output. Does anybody know why?
I wanted to rebuild a calculator with double instead of int to not only get integers as a result.
This is the code:
#include <stdio.h>
using namespace std;
int main(){
printf ("Taschenrechner\n\n");
int zahl1, zahl2;
char rechop;
double erg;
printf ("Gib die Rechnung ein: ");
scanf ("%d", &zahl1);
scanf ("%c", &rechop);
scanf ("%d", &zahl2);
if (rechop == '+'){
erg = zahl1+ zahl2;
printf ("Ergebnis: ");
printf ("%f", erg);
}
else if (rechop == '-'){
erg = zahl1 - zahl2;
printf ("Ergebnis: ");
printf ("%f", erg);
}
else if (rechop == '*'){
erg = zahl1 * zahl2;
printf ("Ergebnis: ");
printf ("%f", erg);
}
else if (rechop == '/'){
erg = zahl1 / zahl2;
printf ("Ergebnis: ");
printf ("%f", erg);
}
else {
printf ("Keine gültige Rechenoperation!");
}
return 0;
}
To decide how many decimal numbers show, you can use %.2f (where ".2" stands for "2 decimals after the comma") in the printf instead of simply %f.
Edit: forgot to say that, by doing that, your result get rounded (and not simply "cut").
There is your code updated (and translated):
#include <stdio.h>
using namespace std;
int main(){
printf ("Calculator\n\n");
int num1, num2;
char simbol;
double res;
printf ("Insert the expression: ");
scanf ("%d", &num1);
scanf ("%c", &simbol);
scanf ("%d", &num2);
if (simbol == '+'){
res = num1+ num2;
printf ("Result : ");
printf ("%.2f", res);
}
else if (simbol == '-'){
res = num1 - num2;
printf ("Result : ");
printf ("%.2f", res);
}
else if (simbol == '*'){
res = num1 * num2;
printf ("Result : ");
printf ("%.2f", res);
}
else if (simbol == '/'){
res = num1 / num2;
printf ("Result : ");
printf ("%.2f", res);
}
else {
printf ("Not a valid expression!");
}
return 0;
}
Your output has zeros after the decimal point, because that's actually what is in the variable (erg) that you are printing.
Your problem is that this line uses integer division:
erg = zahl1 / zahl2;
When the compiler is picking which operation to do, it only looks at the data type of the inputs (which are both int). The result is then converted to be stored into erg, but that doesn't affect the division behavior chosen.
Change the line to:
erg = zahl1 * 1.0 / zahl2;
or
erg = zahl1;
erg /= zahl2;
so that one of the inputs will be type double, and integer division will no longer be involved.
The problem is that you’re doing operations between int (num1 and num2 are declared as int). In order to have decimal numbers you must do operations between float (or double as in your case).
You can declare num1 and num2 as double directly (and change %d to %lf in the scanf and printf).
Another possibility is to do an explicit type cast: type cast is basically a conversion from a type to another and it is explicit because you’re writing it instead of letting the compiler do it for u (in your og program a cast is done by the compiler, after the operation, to fit the int result in the double type variable erg).
So an example is:
result = num1 + num2;
Becomes:
result = (double)num1 + (double)num2;
#include <stdio.h>
#include <stdlib.h>
#define f(x) (1 / (x*x+1))
int main(){
double a,b,h,x,y;
printf("Enter a, b, h: ");
scanf(" %lf %lf %lf " , &a, &b, &h);
// I ask for 3 inputs but the programm needs 4 to run...why is that?
x = a;
while(x<b)
{
y = f(x);
printf("%lf %lf \n", x ,y );
x +=h;
}
system("Pause");
return(0);
}
The problem is with your scanf:
scanf(" %lf %lf %lf " , &a, &b, &h);
^
scanf need to see the next non-whitespace to determine the end of this "0 or more whitespaces", so you'll have to give the 4th value (it can be garbage - as long as it's not whitespace) for scanf to terminate the input.
If you're on Windows, you can hit Ctrl-Z on a new line and press Enter. This will send an EOF to the program, which can also terminate the input. (I suppose you're on Windows because I see system("pause") in your program)
so Im trying to calculate a number raised to a power from user input, using scanf, but i keep on getting a segmentation fault.Does any one know why?This is my code:
int power( int base, int exponent){
int total=1;
int temp = power(base, exponent/2);
if (exponent == 0)
return total; // base case;
if (exponent % 2 == 0)// if even
total= temp * temp;
return total;
if(exponent %2 !=0)// if odd
total =(base * temp * temp);
return total;
}
void get_info(){
int base, exponent;
printf("Enter a base number: ");
scanf("%d", &base);
printf("Enter an exponent: ");
scanf("%d", &exponent);
//call the power function
printf("%d",power(base,exponent));
}
int main(){
//call get_info
get_info();
return 0;
}
Any help would be much appreciated.Thank you.
There's nothing to block the recursion in power:
int power( int base, int exponent){
int total=1;
int temp = power(base, exponent/2); // round and round we go
The solution is to put
if (exponent == 0)
return total; // base case;
at the top of the function. C++ runtime libraries often issue a misleading termination message on a stack overflow such as this.
I'd also be tempted to use an else rather than testing the odd case explicitly. And fix the glaring issue with some missing { and }.
This program compiles fine, but it returns a message "Floating Point Exception" when I run it. I've looked at other threads and the problem appears to be dividing by 0, but I have looked over the program and there's no division by zero in my entire program. I even used the absolute value function in case.
By the way, the program is meant to reduce fractions.
Example input: 6 12, representing the fraction 6/12
Expected output: 1/2
#include <stdio.h>
/*declaring variables*/
int num1, num2, num1b, num2b, gcd, x;
int higher, lower, higher_2, lower_2;
/*declaring functions*/
int find_gcd(int num1, int num2);
void reduce(int numerator, int denominator, int *reduced_numerator, int *reduced_denominator);
int main(void)
{
do
{
printf("enter 2 numbers: ");
scanf("%d %d", &num1, &num2);
reduce(higher, lower, &higher_2, &lower_2);
printf("enter 0 to end program and any number continue: \n");
scanf("%d", &x);
} while(x != 0);
return 0;
}
void reduce(int numerator, int denominator, int *reduced_numerator, int *reduced_denominator)
{
num1=numerator;
num2=denominator;
gcd =find_gcd(numerator, denominator);
*reduced_numerator = (numerator/abs(gcd));
*reduced_denominator = (denominator/abs(gcd));
printf("The GCD is %d/%d\n", *reduced_numerator, *reduced_denominator);
}
int find_gcd(int m, int n)
{
while (n != 0) {
int remainder = m % n;
m = n;
n = remainder;
}
return m;
}
Your main problem is that you are not passing your input values num1 and num2 into your reduce() function. Instead you are passing in the global variables higher and lower. You didn't assign any values to them, but global variables are always initialized to 0 by default. Therfore, you run into the exception, because in reduce() you divide 0 by 0. You can verify that with a debugger.
If I change your main() as follows, then your code is at least working for your test case with 6 and 12 as input:
int main(void)
{
do
{
printf("enter 2 numbers: ");
scanf("%d %d", &num1, &num2);
reduce(num1, num2, &higher_2, &lower_2);
printf("enter 0 to end program and any number continue: \n");
scanf("%d", &x);
} while(x != 0);
return 0;
}
Output:
enter 2 numbers: 6
12
The GCD is 1/2
enter 0 to end program and any number continue:
As indicated in the comments you should also get rid of global and spurious variables. Therefore, you should first delete the following lines in your code:
/*declaring variables*/
int num1, num2, num1b, num2b, gcd, x;
int higher, lower, higher_2, lower_2;
Then let your main() function start the following way:
int main(void)
{
int num1, num2, higher_2, lower_2, x;
...
}
And your reduce() function should read like this:
void reduce(int numerator, int denominator, int *reduced_numerator, int *reduced_denominator)
{
int gcd = find_gcd(numerator, denominator);
*reduced_numerator = (numerator/abs(gcd));
*reduced_denominator = (denominator/abs(gcd));
printf("The GCD is %d/%d\n", *reduced_numerator, *reduced_denominator);
}
So far, you don't use your variables higher_2 and lower_2 in the main() function, but I guess you plan to do so. If not, you can also get rid of them together with parameters 3 and 4 of your reduce() function.
There is another issue with the code you provided (thanks to #user3629249 for pointing it out): You are missing an include for the abs() function. So you need to add the line #include <stdlib.h> at the beginning of your code (include <math.h> will also so the trick, as well as include <Windows.h> on Windows).
I am trying to write a c++ program where you can choose which operation you want to make and then choose the quantity of numbers to calculate the result. And I want to use a getchar function, but I cannot figure it out.
How do you even make int so that it behaves like a variable?
#include <iostream>
#include <stdio.h>
using namespace std;
int main()
{
/*char a_char;
a_char=getchar();
cout<<a_char;*/
int opcode;
int a, b;
int result;
printf("Program for Addition, Subtraction, Multiplication and Division\n");
printf("Enter Your Choice: 1 - Add, 2 - Sub, 3 - Mul, 4 - Div: ");
scanf("%d", &opcode);
printf("Enter First Number:");
scanf("%d", &a);
printf("Enter Second Number:");
scanf("%d", &b);
switch(opcode)
{
case 1:
result = a + b;
printf("%d + %d = %d", a, b, result);
break;
case 2:
result = a - b;
printf("%d - %d = %d", a, b, result);
break;
case 3:
result = a * b;
printf("%d * %d = %d", a, b, result);
break;
case 4:
result = a / b;
printf("%d / %d = %d\n%d %% %d = %d", a, b, result, a, b, a % b);
break;
}
}
Assuming, that you want to input the operation code via getchar, it would look something like this:
opcode = getchar();
and then in your switch you encase the values in singular quotes:
case '1':
....
case '2':
.... and so on
You can use the following code to achieve what you exactly need.
You can replace the following line,
scanf("%d", &opcode);
as
opcode=getchar();
opcode = opcode-'0';
Since getchar will give you ASCII Code. so you need to convert to integer value so you need to subtract '0'.
It is logic: '0' is 48 :)