Incorrect Floating point Output in C Program - c

This is my code
#include <stdio.h>
int main() {
float percentage;
int sp;
int bp;
percentage = (sp-bp)/bp*100;
scanf("%d %d", &sp, &bp );
printf("%.2f%%", percentage);
return 0;
}
Sample input :
150 85
Sample output :
76.47%
but my output is :
-100.00%
Can someone help me fix this?

First of all, you should really read the values before using them:
scanf("%d %d", &sp, &bp);
percentage = ...
Secondly, this:
percentage = (sp-bp)/bp*100;
Does an integer division, so the rest of the division is totally discarded and you will end up with:
(150 - 85) / 85 == 0
0 * 100 == 0.
You should cast one end of the division to float before doing the operation:
percentage = (sp-bp)/(float)bp * 100;
Correct code:
#include <stdio.h>
int main() {
float percentage;
int sp;
int bp;
scanf("%d %d", &sp, &bp);
percentage = (sp-bp)/(float)bp * 100;
printf("%.2f%%", percentage);
return 0;
}

Explanation will add soon.
Code
#include <stdio.h>
int main()
{
float percentage=0;
int sp=0;
int bp=0;
scanf("%d%d", &sp, &bp );
//printf("\n%d%d", bp,sp);
percentage = (sp-bp)/(float)bp*100;
printf("%.2f%%", percentage);
}
Edit
Explain what i changed
As you scanning two integer with one scanf() function.
use scanf("%d%d", &sp, &bp );
Only remove space between two %d %d.
This white space is useless, because scanf() with %d format specifier consume any number of white space. but if you want to scan with %c use that.
scanf() consumes white space for all specifier except for %c, %n, %[…].
see more info on Jonathan Leffler answer
Initialize all variables like this (Declare and Define)
float percentage=0;
int sp=0;
int bp=0;
Because when we declare a variable inside function this is not initiate and have garbage value. This may cause undefined behavior.see C section
Suppose a situation that scanf() cant work properly and the integers sp and bp values remain with defaults. If we don't initiate them, garbage value remains.
Do declare and define at one time and initiate to zero. see
more on declare define
Add (float) explicit conversion to the division.
(sp-bp)/(float)bp*100;
In C result number of An integer that divides to another integer converted to integer and you lost decimal part because that is truncated.
see this

Related

I'm unreasonably getting zero as an output and I can't figure out why

I'm a begginer programmer and I've been experimenting with this code but I can't figure out why it's giving me zero. I've checked for integer divison , and wrong place holders but I can't find any . I also believe I'm using the correct format for every function such as printf , scanf etc. can anyone hepl ?
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int main()
{
double theta , fr , a, pi = 3.1459;
printf("Enter the value of a \n");
scanf("%f",&a);
theta = atan2(a,27.5);
printf("%f",theta);
fr = 1.67*pow(10,-6)*sin(theta);
printf(" frequency = %f",fr);
return 0;
}
You need to use the correct format specifiers for every data type. Your variables are doubles so you need to use %lf for scanning.
You need to learn how to debug programs yourself. If you add one printf mode the problem becomes obvious:
printf("Enter the value of a \n");
scanf("%f",&a);
printf("%f\n", a);
https://godbolt.org/z/cj3zo6Yqn
It is prints zero 0. So scanf did not scan properly.
Changing to
scanf("%lf",&a);
Resolves the problem.
https://godbolt.org/z/jcjrYaG5j

Polynomial multiplication (ax+b)*(cx+d). Strange output when any co-efficient is floating number

Please see the code below.
#include <stdio.h>
int main()
{
int a, b, c, d;
int p2, p1, p0;
printf("Enter a:");
scanf("%d",&a);
printf("Enter b:");
scanf("%d",&b);
printf("Enter c:");
scanf("%d",&c);
printf("Enter d:");
scanf("%d",&d);
p2 = a*c;
p1 = a*d + b*c;
p0 = b*d;
printf("The product is: %dx^2+%dx+%d\n",p2,p1,p0);
return 0;
}
Output is as follows:
Enter a:1.5
Enter b:Enter c:Enter d:The product is 3x^2+0x+0
Can anyone explain this? Once we give 1.5, it is not accepting the values for remaining co-efficients. How did we get that output?
Declaration
Declare all parameters as double instead of int. (a, b, c, d, p0, p1, p2)
Double format
When using %d, an int is expected.
Use %lf when working with doubles.
This refers both to scanf and printf.
Code:
#include <stdio.h>
int main()
{
double a, b, c, d;
double p2, p1, p0;
printf("Enter a:");
scanf("%lf",&a);
printf("Enter b:");
scanf("%lf",&b);
printf("Enter c:");
scanf("%lf",&c);
printf("Enter d:");
scanf("%lf",&d);
p2 = a*c;
p1 = a*d + b*c;
p0 = b*d;
printf("The product is: %lfx^2+%lfx+%lf\n",p2,p1,p0);
return 0;
}
First and foremost: the 1.5 in the standard input is not a a floating point value. It's a string of characters which may be interpreted as floating point value. It's also a string of characters that may not be interpreted entirely as an integer.
When scanning it, the 1 may be consumed to scan a value for a. But then the . is encountered, which may not be part of of a character sequence that stands for the value of an integer. So scanf will not consume it, it will stay in the input buffer until some other operation will deal with it.
But you call scanf again, and tell it to expect an integer. It still sees the ., which it can't handle. So it returns without consuming anything or writing anything into the argument you've given it. It reports the result of the operation in its return value, that you neglect to check. On the whole, your code doesn't take any error handling into account. It's written with the assumption scanf will always succeed, which is not realistic. You can read about scanf's return value here.
Beyond that, you don't initialize any of your variables. That leaves them with indeterminate values. If scanf succeeds, those variables get assigned something else and your program runs successfully. But if scanf fails they don't, and you use those indeterminate values, resulting in your program having undefined behavior. There's no point trying to understand undefined behavior. You should fix your code instead. And you do that by handling failure properly. How you choose to handle scanf's failure is up to you.

loop condition with variable input with scanf - C

#include <stdio.h>
#include <stdlib.h>
int main() {
unsigned int n0;
scanf("%d", &n0);
const unsigned int n = n0;
short unsigned int A[n];
short unsigned int d, x, y, k;
short int l, r;
int i, j;
for (i = 0; i < n; i++) {
scanf("%d", &A[i]);
}
scanf("%d", &d);
for (i = 1; i <= d; i++) {
scanf("%d %d", &x, &y);
}
return 0;
}
Hi, I'm a total newbie with C and stumbled across a situation that amazed me a lot. In the above code, I would like to ask the user to input some number d, and then to input d pairs of point coordinates. But to my surprise the program ends executing after inputting first pair of (x,y), no matter what value of d greater than 1 is input first. It doesn't happen if I assign value to d in code (e.x. d = 5;). What may be the reason? Is the value assigned to the variable via the scanf statement somehow different and cannot be used in a loop condition?
Pay attention to the warnings that you get when compiling your code. One of the warnings should be as follows:
a.c:19:12: warning: format specifies type 'int *' but the argument has type
'unsigned short *' [-Wformat]
scanf("%d",&d);
~~ ^~
%hd
Using %d causes scanf cast a pointer to short as a pointer to int, leading to undefined behavior. It looks like in your case the upper portion of an int gets stored in a short, while the bottom portion gets dropped. For numbers undef 216 the upper part is zero, so the subsequent loop iterates zero times.
Fixing all warnings will eliminate this problem
scanf("%hu", &d);
... // Fix other scanf calls as well.
Note: There is no good reason for making loop variables short.

How do you calculate interest on a loan with different rates?

I think it's obvious I don't understand. How do you tell the computer in C to decide which is the appropriate interest rate and then calculate and display it. This is the best I could come up with and I have to hand this as an assignment tomorrow. I had not clue it would be this difficult.
#include <stdio.h>
int main (void)
{
float time;
float principal;
char response[15];
float rate1, rate2,rate3,rate4;
rate1=.04,rate2=.05,rate3=.06,rate4=.07;
float SimpleInterest1;
float SimpleInterest2;
float SimpleInterest3;
float SimpleInterest4;
SimpleInterest1=principal*time*rate1;
SimpleInterest2=principal*time*rate2;
SimpleInterest1=principal*time*rate3;
SimpleInterest2=principal*time*rate4;
printf("Please enter principal\n");
scanf ("%f",&principal);
printf ("Please enter time\n");
scanf ("%f",&time);
if (principal <= 5000)
{
printf ("%f",&SimpleInterest1);
}
printf ("Do you still want the loan?\n");
scanf ("%s",response);
return 0;
}
As it has been already said: do not forget to ask for principal value using
scanf.
Then, use if-else if-else-statements to know in which interval principal lies.
Then, inside each statement, assign interest to the right value.
Then assign time to the right value (you can scanf it if you have to) before calculating the interest.
Also, check if the interest has to be recomputed each year on the
new debt. If this is the case, then the formula should be
debt = principal * (1 + rate)^time.
You can #include <math.h> to use the pow function that computes the power of a float or a double.
Then just printf("%f", debt);.
Aparté:
Michael Overton's book "Numerical Computing with IEEE Arithmetic" pp.82-86 explains pretty well how to compute a compound interest with a stable algorithm, because the naive way to compute it using pow can involve a loss of accuracy.
First off, these two lines are probably a typo:
SimpleInterest1=principal*time*rate3;
SimpleInterest2=principal*time*rate4;
They should become this:
SimpleInterest3=principal*time*rate3;
SimpleInterest4=principal*time*rate4;
Next, if your asking about i/o (input/output), then here's a basic run through:
You use printf( char *format, ...) to output information.
You use scanf( char *format, ...) to do basic input.
Where format is one of the following (this is the basics):
%s : Argument is expected to be of type char*
%i : Argument is expected to be signed int
%f : Argument is expected to be float (use also for double in printf)
%u : Argument is expected to be unsinged int.
When you use scanf, you should check the return value and clear the input buffer, examples will follow:
void clear_buffer() {
// Note that ch is int not char, this is important
int ch;
while( (ch = getchar()) != EOF && ch != '\n');
}
int answers = 0;
float value = 0.0;
do {
// Scanf returns the recieved number of args that fit the format string
answers = scanf( "%f", &value );
clear_buffer();
if (answers == 0) {
continue;
}
} while (value > -0.1 && value < 0.1);
The above may not work as I mainly work with unsigned integers, but it should provide a good foundation at the very least.
You use if...else if....else to determine the formula to use.
Lastly, you should calculate the SimpleInterest AFTER you get a value for time and principal; the c parser cannot 'see into the future'

query regarding sprintf() and scanf()

Take for example
int i=10,j;
float b=3.14,c;
char str[30];
sprintf(str,"%d%f",i,b);
sscanf(str,"%d%f",&j,&c);
printf("%d ----- %f\n",j,c);
OUTPUT :- 103 ----- 0.1400000
As you can see, initially i=10 and b=3.14.
I want that j=10 and c=3.14 by using sprint() and sscanf().
The problem I am facing is that the compiler assigns j=103 and c=0.140000.
Is there any way to get rid of this problem in sscanf()?
Add one space to sprintf. Change:
sprintf(str,"%d%f",i,b)
to
sprintf(str,"%d %f",i,b)
Aside: It would be also safer to use snprintf here:
snprintf(str, sizeof str, "%d %f", i, b)
The best way will be to separate the numbers, using a different sign, but if you know that the first int is 2 chars long you can specify it:
sscanf(str,"%2d%f",&j,&c);
// ^^
You are missing a space
Change
sprintf(str,"%d%f",i,b);
to
sprintf(str,"%d %f",i,b);
#include <stdio.h>
int main()
{
int i=10,j;
float b=3.14,c;
char str[30];
sprintf(str,"%d %f",i,b);
sscanf(str,"%d%f",&j,&c);
printf("%d ----- %f\n",j,c);
return 0;
}
output
~ > ./a.out
10 ----- 3.140000
The %d conversion specifier in sscanf will match any number of contiguous numeric characters in the buffer pointed to by str till it encounters a non-numeric character which it can't match. This will cause the integral part of the float to be read as part of the int value. Therefore you must have a way to separate where you integer ends and float starts in the string str. You can put any non-numeric character as a sentinel to separate int value from the float value.
int i = 10, j;
float b = 3.14, c;
char str[30];
// a # to separate the two values, can be any non-numeric char so that it
// is not mistaken for a digit in the int or float value
sprintf(str,"%d#%f", i, b);
// match the separator character to read int and then float
sscanf(str, "%d#%f", &j, &c);

Resources