Double showing a lot of zeros with printf - c++

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;

Related

A simple calculator using C about conversion of Fahrenheit to Celsius, and vice versa

Good day! I tried to make a simple calculator using C for my first project about conversion between Fahrenheit to Celsius, and vice versa. But it's not working, can someone tell me what I miss?
Here's my code:
#include <stdio.h>
int main()
{
double temp, fahrenheit, celsius;
char answer[2];
printf("Type 'CF' if you want to convert from celsius to fahrenheit, and 'FC' if you want to convert from fahrenheit to celcius: ");
fgets(answer, 2, stdin);
fahrenheit = (temp * 1.8) + 32;
celsius = (temp - 32) * 0.5556;
if(answer == "CF"){
printf("Type the temperature here: ");
scanf("%lf", &temp);
printf("Answer: %f", fahrenheit);
}
else if(answer == "FC"){
printf("Type the temperature here: ");
scanf("%lf", &temp);
printf("Answer: %f", celsius);
}
return 0;
}
calculator
You can't compare strings like this in C. There strcmp and strncmp functions. Besides this C strings are ended with \0 symbols, so your code should be something like this:
#include <stdio.h>
#include <string.h>
int main()
{
double temp, fahrenheit, celsius;
char answer[3];
printf("Type 'CF' if you want to convert from celsius to fahrenheit, and 'FC' if you want to convert from fahrenheit to celcius: ");
fgets(answer, 3, stdin);
fahrenheit = (temp * 1.8) + 32;
celsius = (temp - 32) * 0.5556;
if (strcmp(answer, "CF") == 0) {
printf("Type the temperature here: ");
scanf("%lf", &temp);
printf("Answer: %f", fahrenheit);
} else if (strcmp(answer, "FC") == 0){
printf("Type the temperature here: ");
scanf("%lf", &temp);
printf("Answer: %f", celsius);
}
return 0;
}
Use strcmp for
(answer == "CF"){
i.e.
strcmp(answer, "CF") == 0

calculate a number raised to a power from user input, using scanf,

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 }.

C Program Skipping if Statements Even When Conditions Are Met

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.

Error C2078: too many initializers

Why does this code not work? My IDE is Visual Studio 2013.
#include <stdio.h>
float tempatureGuide(float F, float C);
#define FREEZING_PT 32.0f
#define SCALE_FACTOR (5.0f/9.0f)
int main(void)
{
float fahrenheit = 0.0;
float celsius = 0.0 ;
int convertTemp;
printf ("Enter 0 to calculate Celsius or 1 to calculate Fahrenheit: ");
scanf ("%d", &convertTemp);
if (convertTemp == 0)
{
// compute Celsius
printf("Enter Fahrenheit temperture: ");
scanf("%f", &fahrenheit);
celsius = ((fahrenheit - FREEZING_PT) * SCALE_FACTOR);
printf("Fahrenheit = %f and Celsius = %f\n", fahrenheit, celsius);
float tempatureGuide(fahrenheit, celsius); // Error here
}
else
{
// compute fahrenheit
printf("Enter the temperature in degrees fahrenheit\n\n");
scanf("%f", &fahrenheit);
celsius = (SCALE_FACTOR)* (fahrenheit - FREEZING_PT);
printf("The converted temperature is %f", celsius);
float tempatureGuide(fahrenheit, celsius); // and here
}
return (0);
}
float tempatureGuide(float F, float C){
if (F < 32 || C < 0)
printf("It is freezing!");
else if (F <= 60 || C <= 16)
printf("It is cold");
else if (F >= 70 || C >= 21)
printf("It is just right");
else if (F >= 82 || C >= 28)
printf("It is warm");
else if (F > 95 || C > 35)
printf("It is hot");
else
printf("Please enter a number!");
return (0);
}
The goal here is to add to the converting temperature project I did earlier and add an if else statement function to it that comments on the temp. The error I get is
Error 3 error C2078: too many initializes
on both the lines where I call my function. I searched for an answer but couldn't find any.
This line looks like an attempt at a C++ initialization of a float with one too many arguments (hence the "too many initializers" error), not like a function call.
float tempatureGuide(fahrenheit, celsius);
Presumably you want to call the function and store the result in a variable:
float temp = tempatureGuide(fahrenheit, celsius);
Or just call the function and ignore the return value:
tempatureGuide(fahrenheit, celsius);
Especially since your function always returns 0, so one might question the need for a non-void return type.
You need to call a function
float tempatureGuide(float fahrenheit, float celsius) { //...}
as
float retval = tempatureGuide(fahrenheit, celsius);
or least
tempatureGuide(fahrenheit, celsius); // not need to use return value
Only.
That is just a simple error. Please change 2 lines of code where you are calling tempatureGuide(fahrenheit, celsius); function as follows.
float tempatureGuide(fahrenheit, celsius); --> float ret = tempatureGuide(fahrenheit, celsius);
I tested the same in my VS2013 as you are using the same with the mentioned changes. I am able to compile and run it successfully. See the attachment.
Just call the function and return it to a variable of the same type.

Using Char in an if statement C++

Folks, I'm trying to use an 'if' statement with a char variable, but it doesn't seem to notice when the 'yes' condition is met. I don't know if there's a way to do this without the array. Here's my code below. Any help is much appreciated.
// Running times calculator
# include <iostream>
# include <math.h>
using namespace std;
int main ()
{
float cTime;
float gTime;
float cDist;
float gDist;
float min;
float sec;
float cMin;
float cSec;
float p1000;
char response[1];
int blank;
printf ("Welcome to the running times calculator.\n\nEnter your completed race distance in metres: \n");
scanf ("%f", &cDist);
printf("Enter your completed race time. Type minutes, hit enter. Type seconds, hit enter\n");
scanf ("%f" "%f", &cMin, &cSec);
cTime = cSec+(60*cMin);
p1000 = pow(1000/cDist,1.1)*cTime;
printf ("Would you like to enter another race time to improve prediction accuracy? \n");
scanf ("%s", &response);
if(response == "yes")
{
printf ("Enter your completed race distance in metres: \n");
scanf ("%f", &cDist);
printf("Enter your completed race time. Type minutes, hit enter. Type seconds, hit enter\n");
scanf ("%f" "%f", &cMin, &cSec);
cTime = cSec+(60*cMin);
p1000 = ((pow(1000/cDist,1.1)*cTime)+p1000)/2;
}
printf ("What is your goal race distance in metres? \n");
scanf ("%f", &gDist);
gTime = pow(gDist/1000, 1.1)*p1000;
min = gTime/60;
sec = remainder(gTime,60);
if (sec < 0)
{
sec = sec + 60;
min = min - 1;
}
printf ("Your predicted time for a race of %.0f metres is %.0f minutes and %.0f seconds", gDist, min, sec);
scanf("%f", &blank);
return 0;
}
You got a few problems with the way you treat your char array.
char response[1]; You create an char array that consists of one character here but then you treat it as a string in these lines:
scanf ("%s", &response);
if(response == "yes")
also note that you can't simply compare a char array and a string literal with == all you'd do would be comparing addresses. You'd either have to use strcmp() or better use std::string.
Didn't check all the code, but you use an
operator ==
that doesn't work with a char [], it's for string
use strcmp instead.