C Programming Rounding User's Input [duplicate] - c

This question already has answers here:
How do I restrict a float value to only two places after the decimal point in C?
(17 answers)
Closed 6 years ago.
I've just started a class in C Programming, and while I have some background knowledge in JAVA, I'm trying to transition to this programming language. I have a project where I have to round user's input from something like 1.3333 to only two decimal places.
What I have so far is this:
#include <stdio.h>
int main (void)
{
//v is my variable for the value which the user will input
//Declaring variable as floating
float v;
printf("Enter your value: \n");
scanf("%.2f", &v);
v = 0;
printf("The rounded version is: %.2f");
return 0;
}
This is what I have so far based off of what I've read in my book and this link: Rounding Number to 2 Decimal Places in C which my question is different from because it involves user input. My professor does say that I can't use a library function and need to use simple type casts to calculate it. This makes me feel that what I have might be wrong. Would the #include <stdio.h> be considered a library function? Given this information, is my thought process on the right track? If not, then would I do something like divide by variable by 100? Maybe %e for scientific notation?
Thanks ahead of time! Only asking for specific information, not coding or anything. Really want to understand the "hows" and "whys".

First of all #include is a command that you need in order to include and use function that c provides for example for scanf you need to include library.
To round the number in two decimals without using %.2f in scanf you could write:
int x= (v*1000);
if(x%10>6) x=x/10+1 ;
else x= x/10;
printf("%d.%d",x/100,x%100);

I think your professor aims not so much in user input but rather in understanding what happens when converting basic datatypes. Rounding, or at least cutting off digits, without library functions could look as follows:
int main (void)
{
//v is my variable for the value which the user will input
//Declaring variable as floating
float v;
printf("Enter your value: \n");
scanf("%f", &v);
v = float((int)(v*100))/100;
printf("The rounded version is: %f", v);
return 0;
}
Input/Output:
Enter your value:
1.3333333
The rounded version is: 1.330000

Here is a working example that rounds properly without using any library calls other than stdio.
#include <stdio.h>
int main (void)
{
float v;
printf("Enter your value: \n");
scanf("%f", &v);
v = (float)((int)(v * 100 + .5) / 100.0);
printf("The rounded version is: %f\n",v);
return 0;
}
Output:
jnorton#mint18 ~ $ ./a.out
Enter your value:
3.456
The rounded version is: 3.460000

Related

Passing a variable by value, printf doesn’t show the correct result

I'm a university student and in one of my exercises to train c programming I got stuck on an error with a print function. I used CLION which was great but now moved on into VS Code, because the teacher say it´s the most used in a professional environment. What are your thoughts on it?!
main.cpp
#include <stdio.h>
#include "complex.h"
int main (){
Complex x;
inputNmbr(x);
printNmbr(x);
return 0;
}
complex.h
#include <stdio.h>
typedef struct{
float r,i;
}Complex;
Complex inputNmbr(Complex x){
printf("Input an imaginary number (R +/- I):\n");
scanf("%f %f", &x.r, &x.i);
return x;
}
void printNmbr (Complex x){
printf("Imaginary number: %.2f +/- %.2f\n", x.r, x.i);
}
Terminal
aluno#aluno-VirtualBox:~/Desktop/Programação por objetos/P1/EX2$ ./main\
Input an imaginary number (R +/- I):
1 2
Imaginary number: 0.00 +/- 0.00
So the printf function always shows 0 0 and I´m not understanding the source of this error.
P.S. After being attacked about the C/C++ tag I´m posting the exercise (the reason why I put the both tags is related to this):
Write a module in C that allows working with complex numbers.
Create the files complex.h and complex.cpp where you should implement the following functionalities:
The definition of data structure (Complex) to represent a complex number
(r, i);
A function that reads a complex number;
A function that writes a complex number in the format: #.#+/-#.#i (where +/- depends on the sign of the imaginary part);
A function for each of the following operations:
Addition: a+bi+c+di=(a+c)+(b+d)i
Subtraction: a+bi-c+di=(a-c)+(b-d)i
Multiplication: (a+bi)*(c+di)=(ac-bd)+(bc+ad)i
Division:
(a+bi) / (c+di)=((ac+bd)/(c^2+d^2))+((bc-ad)/(c^2+d^2))i
I am not going through all your execise, however, the problem of your incorrect printf is that your struct variable x is passed "by value" to the function inputNmbr. This means that when invoking it, a copy of your variable is created and put on the function stack, and even if you modify the value inside the function, the modification is not reflected in the original variable.
A solution can be to change the input parameter of inputNmbr function so to make it a pointer. For example:
void inputNmbr(Complex * x){
printf("Input an imaginary number (R +/- I):\n");
scanf("%f %f", &(x->r), &(x->i));
}
In this case, your main will be:
int main (){
Complex x;
inputNmbr(&x);
printNmbr(x);
return 0;
}
Another method of doing this would be having in main:
Complex x = inputNmbr();
and in your fn definition:
Complex inputNmbr(){
Complex a;
printf("Input an imaginary number (R +/- I):\n");
scanf("%f %f", &a.r, &a.i);
return a;
}
The choice of a "return" vs using pass by address to return is stylistic but may also depend on a standard depending on your professor.

How to fix C function giving wrong summation values

I have made a simple addition function, but getting wrong summation values, sorry if it is a naive thing to look for. But really want to know why is this happening. I want an alternative solution for this. Thanks in advance!
I am using notepad++ to write the code, and gcc compiler in the windows command prompt to execute the code.
#include <stdlib.h>
#include <stdio.h>
float addit(float num1, float num2)
{
float sumit;
sumit = num1 + num2;
return sumit;
}
int main()
{
float num1, num2;
float answer = 0.000000;
printf("Enter first number: ");
scanf("%f", &num1);
printf("Enter second number: ");
scanf("%f", &num2);
answer = addit(num1, num2);
printf("The summation is: %f", answer);
return 0;
}
The expected output of the addition of 2345.34 and 432.666 is 2778.006.
But, after execution it shows 2778.006104.
Windows cmd window showing execution result as 2778.006104
Welcome to the wonderful world of floating point values! Consider this: between 0 and 1, there are infinitely many numbers. There's 0.1, and there's 0.01, and there's 0.001, and so on. But computers do not have infinite space, so how are we supposed to store numbers? Our solution was to limit the precision of the numbers we stored. As others have mentioned, java's float data type only has 6 or 7 digits of accuracy (in base 10). Because of this, you cannot necessarily guarantee that the result of a mathematical operation on floats will be 100% accurate. You can only be sure that the first 6-7 digits of the result will be.

5/9 is not taking by the C compiler to Calculate fc [duplicate]

This question already has answers here:
Division result is always zero [duplicate]
(4 answers)
Dividing 1/n always returns 0.0 [duplicate]
(3 answers)
Closed 5 years ago.
I'm stuck in a Code where I have to convert a temperature given by the user (in Fahrenheit) to degree Celsius. But unfortunately it's formula is not working with C Compiler.
#include<stdio.h>
#include<stdlib.h>
void c_f();
//void f_c();
float c,f,fc,fc1;
int main()
{
c_f();
// f_c();
return 0;
getch();
}
void c_f()
{
printf("\n Enter the temperature (in *F) to covert it into Celsius: ");
scanf("%d",&f);
fc=((5/9)*(f-32));
printf("\n %f*C",fc);
}
fc=((5/9)*(f-32));
Because 5 and 9 are integers, the arithmetic calculation is done at integer level, thus 5/9 == 0.
You should change it to floating point:
fc = ((5.0f / 9.0f) * (f - 32.0f));
Besides, format specifier %d is used for integers. If you want to read a floating point number, use %f:
scanf("%f", &f);
The result should be right now.
You have to use the correct format specifier which will be scanf("%f",&f) in this case.
Also fc=((5.0/9.0)*(f-32)), otherwise integer division yields 0.(Integer division truncates).5/9.0 will also work.
It is useless to put getch() after return statement. It will never reach upto that line.
What happens in your version?
Actually when two integers are divided the result is the quotient. If there any fractional part it is discarded. If you divide 5 by 9 the result will be 0.555.... When fractional part discarded it will be 0. So you always get 0.
Whenever you need an outcome of a division not t truncate you must make one of them floating point. That ensures that it(result) will not truncate.
So the program would be
#include<stdio.h>
#include<stdlib.h>
void celciusToFahreinheit();
float fahr_temp,celc_temp;
int main()
{
celciusToFahreinheit();
return EXIT_SUCCESS;
}
void celciusToFahreinheit()
{
printf("\n Enter the temperature (in *F) to covert it into Celsius: ");
if( scanf("%f",&fahr_temp) != 1 ){
fprintf(stderr,"Error in input\n");
exit(EXIT_FAILURE);
}
celc_temp=((5.0/9.0)*(fahr_temp-32));
printf("\n %f*C",celc_temp);
}
Apart from the problem few things would be - Using readable function name and checking the return value of scanf.

Program output is different from manual calculation why is this happening? C language [duplicate]

This question already has answers here:
Is floating point math broken?
(31 answers)
Closed 5 years ago.
#include <stdio.h>
#define s scanf
#define p printf
void main (){
int P,I,A;
float T,R;
clrscr();
p("PRINCIPAL: ");
s("%i",&P);
p("RATE: ");
s("%f",&R);
p("TERM: ");
s("%f",&T);
R = R/100;
I = P*R*T;
A = P+I;
p("I: %i\nMA: %i",I,A);
getch();
}
This really bugs me, if i put PRINCIPAL: 1200 RATE: 3 TERM:1 I: 35 MA: 1235 but if you compute in manually the answer should be I: 36 MA: 1236 the number is decreasing by 1. Why is it happening? why does the answer differ from computer and manual computing?
You try to typecast float to int that causes some data loss. Just like we can not store the big object in the small bag.
#include <stdio.h>
#define s scanf
#define p printf
int main (){
int P;
float T,R,I,A;
p("PRINCIPAL: ");
s("%i",&P);
p("RATE: ");
s("%f",&R);
p("TERM: ");
s("%f",&T);
R = R/100;
I = P*R*T;
A = P+I;
p("\nI: %f\nMA: %f",I,A);
return 0;
}
Your problem is with typecasting, please research on this subject a look at this, it's a little bit hude to explain in a simple text here.
But I can tell you, you are problably losing information when casting from float to int, because this two primitive types in C have diferent max length.
You can see changin the int variables to float and running your own program again, like this:
#include <stdio.h>
#define s scanf
#define p printf
void main (){
float P,I,A;
float T,R;
p("PRINCIPAL: ");
s("%f",&P);
p("RATE: ");
s("%f",&R);
p("TERM: ");
s("%f",&T);
R = R/100;
I = P*R*T;
A = P+I;
p("I: %f\nMA: %f",I,A);
getch();
}
This will produce your desired output, just in float.
Your problem is in the conversion of float to int. If you do your program with everything typed as float, you get the expected results:
#include <stdio.h>
#define s scanf
#define p printf
int main (){
float P,I,A;
float T,R;
p("PRINCIPAL: ");
s("%f",&P);
p("RATE: ");
s("%f",&R);
p("TERM: ");
s("%f",&T);
R = R/100;
I = P*R*T;
A = P+I;
p("I: %f\nMA: %f",I,A);
return 0;
}
outputs:
PRINCIPAL: 1200
RATE: 3
TERM: 1
I: 36.000000
MA: 1236.000000
However, when you convert your float values to int, you just take the integer part; everything to the right of the decimal point gets deleted. So, even though it's printing as 36.000000 when I do it, it's possible that the value of I may be coming out to something like 35.9999999, due to imprecision in floating-point math, and simply displaying as 36.000000 due to rounding in the display process. In this case, you'll just get the 35, and lose everything else.
To solve your problem, either leave everything as a float, or convert your floats to ints by rounding them—for example, by using lroundf in math.h—instead of just casting them.

Issues working with complex.h

I have written a small c code to find the sqrt of a number . And i want the program to even find the sqrt of a negative number . I came across complex.h and couple of functions to perform the complex arithmetic .I have made use of them and i'm getting a couple of warning messages while compiling.The code does not calculate the square root of positive and negative numbers correctly .
1)What is the correct format specifier for printf and scanf for printing and taking in complex numbers ?
Please let me know where exactly i'm going wrong .I'm using a gcc compiler and OS is Ubuntu 12.04 LTS.I have attached the code and the outputs.
#include <stdio.h>
#include <math.h>
#include <complex.h>
int main()
{
float complex var,op;
printf(" Enter the number : " );
scanf("%lf",&var);
op=csqrt(var);
printf("%lf \n",op);
}
o/p Enter the number : 4
0.011604
Another o/p Enter the number : -4
-0.011604
From C99:
6.2.5/13 Types
Each complex type has the same representation and alignment
requirements as an array type containing exactly two elements of the
corresponding real type; the first element is equal to the real part,
and the second element to the imaginary part, of the complex number.
So as one possibility, you can use:
scanf("%f %f",&var[0], &var[1]);
To read in a float complex type, with whitespace separating the real and imaginary parts.
To find the square root of a negative number you can use the following code,
printf(" Enter the number : " );
scanf("%lf",&var);
if(var < 0)
{
op=csqrt(-var);
printf("The square root is %lfi \n",op);
}
else
{
op=csqrt(var);
printf("The square root is %lf \n",op);
}
printf and scanf don't have native support for complex numbers, but that's OK; you can write the format easily enough:
scanf( "%f %fi", &re, &im );
now re and im contain the real and imaginary parts (although it won't accept spaces after the + or -, so 3 + 2i will be rejected, but 3 +2i and 3+2i are fine.
The same goes for printing;
printf( "%f%+fi", re, im );
will print the variables in 3+2i form.
Finally, though it doesn't seem to be directly part of your question, the square root of a negative number is simply the square root of the positive value multiplied by i.

Resources