C - compare read in float to zero - c

In my programm I have several float variables that I need to compare to 0. Those variables are being read in through printf.
float a;
scanf("%f", &a);
if (a=0)
{
printf("a is zero");
return 0;
}
But it doesn't work when I give in a 0 through scanf. "a is zero" isn't displayed. It doesn't work with (a=0.0) and doesnt work with (a=0.0f) or (a=0.). The only way I managed to do it is with (0 < a && a < 0.0000000000001)
but I feel like this is not a very good way to do it.
What did I do wrong? Why doesn't it recognize the 0 I input in with scanf as 0?

Just change "=" to "==". You can write "if" statement to following style:
if (CONSTANT == variable)

Change the assignment operator(=) to Comaparison Operator (==) in if Condition.
In addition to that do type casting while comparing the value
if (a==(float)0)

Related

Why is the output different in the short version of if condition when compared to its expanded version?

int a = 0;
a = 7 > 2 ? printf("6") : printf("4");
printf ("%d",a);
The ouput of this block is :
61
I tried the code in its expanded form
int a = 0 ;
if(7>2)
{
printf("6");
}
else
{
printf("4");
}
printf("%d",a);
Here I the output was:
60
I would like to get an explanation on why the output differs.
The first statement assigns the return value of printf to a. printf returns the number of bytes that were written. In this case that is 1. In the second expanded version, a is not assigned. Here is an actually equivalent version to the original:
int a = 0;
if(7>2)
{
a = printf("6");
}
else
{
a = printf("4");
}
printf("%d",a);
They are completely different.
To make them identical:
int a = 0 ;
if(7>2)
{
a = printf("6");
}
else
{
a = printf("4");
}
printf("%d",a);
cond?val1:val2 is the ternary operator. It is not supposed to be a control structure (like if, for or while). It is an operator. To build expression (things that have a value) rather than instruction (things that does things).
Frontier is fuzzier in C than in other languages, because instructions have a value (including void) and expression have potential side-effects.
But, well, you use cond?val1:val2 when you want to get the result. As you did, since you assigned the result to a.
And the result here is the result of printf("6"), that is 1, since printf returns the number of printed characters. Note that there is no real doubt, since even if 7 were smaller than 2, result would still have been 1. Since you print that result, it is normal to have a 1 printed after the 6.
(Just to be clear, even if I assume you know that already, what you did is print string "6" and then number 1, which is the result of 1st printf. Exactly as if you did
printf("%d",printf("6"));
which 1st prints "6", then pass the result to the outer printf to print what the inner printf returned, that is 1)
In your second code, you do nothing to change a's value, and you ignore the result of printf.
Your examples aren't equivalent. To be equivalent, the second one should say a=printf(... everywhere. After which a will get assigned the number of characters printed, 1.
The conditional operator (e1 ? e2 : e3) is not a "short version of if condition", although it has some similarities with an if ... else construct. The conditional operator yields a value (which you assign to a in your first example); an if ... else construct does not have a value.
So, your first example assigns a value to a, because it is written in the form of an assignment statement; that value is the 1 returned by the call to the printf function. To get similar behaviour in your second example, as others have said, you need to also assign the value returned by printf inside the if ... else blocks.
Alternatively, to make the first case work like the second, you can skip the assignment and use the conditional operation to determine the argument that is passed to the printf call:
int main(void)
{
int a = 0;
printf(7 > 2 ? "6" : "4");
printf("%d", a);
return 0;
}

Can anybody explain the error in the program i made, can anybody why i didn't workout?

how is your day :),
Take a look at the below program, the program written below is to calculate the sum of first n natural numbers, the problem is that i get the sum of n-1 natural numbers, can anybody explain why ?
and can anybody also explain why a-- instead of --a.
#include<stdio.h>
main()
{
int a,sum;
printf("Enter a number.");
scanf("%d",&a);
sum=sumnat(a);
printf("Sum of the first %d natural numbers is %d.",a,sum);
}
sumnat(a)
{
int b;
if(a==0)
{
return 0;
}
else
{
b=a+sumnat(--a);
return(b);
}
}
There were several errors, the greatest of which was undefined behaviour in the expression which uses a and also a modified value of a. You should also define your function properly, not rely on default values provided by the compiler.
#include <stdio.h>
int sumnat(int a); // function prototype
int main(void) // correct signature
{
int a, sum;
printf("Enter a number. ");
scanf("%d", &a);
sum = sumnat(a);
printf("Sum of the first %d natural numbers is %d.", a, sum);
return 0;
}
int sumnat(int a) // function has a return type and argument type
{
if(a == 0)
{
return 0;
}
return a + sumnat(a - 1); // there was no need to decrement `a`
}
Program session
Enter a number. 5
Sum of the first 5 natural numbers is 15.
Your program works for me, using gcc on Mac OSX. However, it will not work everywhere, because of this line:
b=a+sumnat(--a);
--a decrements a, but if it does so before the addition, then your result will be wrong. I'm not sure C is required to evaluate expressions strictly left-to-right (I don't think it is). At any rate, since you don't use a after that line, you could fix things this way:
b=a+sumnat(a-1);
As #self says, you should fix the program to handle negative values, and it would be a good idea to consider what is the largest natural number whose sum you can compute this way (and why that is).
There is a difference between them. One first subracts from a and than goes in the function while the other frist goes in... so it never gets subracted and you go to inifinit stack.
"and can anybody also explain why a-- instead of --a"
When you use the prefix operator --a the decrease is done before anything else, while the postfix operator a-- happens after the rest of the expression is resolved, so, lets say, while debugging your code, in a particular moment, a = 5
since the line
b=a+sumnat(--a);
is using the prefix version of the operator, the decrement would happen immediately, making a=4 and then the function sumnat would be called with argument 4
b=a+sumnat(a--);
in this case the postfix operator is being used, so first the function sumnat would be called with the argument 5, since that is the value of a in that moment, then, only when the function returns a value (which would never happen in your example, since it would be called multiple times with the same value, never reaching 0) the decrement would happen

my binary search function doesn't work properly

1st of all, sorry my english, it's not my mother language.
Hello everyone, I'm having a problem with my binary search function. I need to make a recursive function(using C language) of binary search, using the boolean type, here it is:
bool binary_search(int x, int array[], int m, int n){
int middle=(m+n)/2;
if(m>n) return(0);
else if(x == array[middle]) return(1);
else if(x < array[middle]) return(binary_search(x, array, m, middle-1));
else return(binary_search(x, array, middle+1, n));
}
here is the call in the main function:
printf("type the element to search: \n"); scanf("%d", &x);
if(binary_search(x, A, 0,dim-1)) printf("Found!\n");
else printf("Not found!\n");
The problem is, it always return "not found" even if the element is not in the array. I tried to change the logic inside the if command, but it just made all results become "found". If anyone can help, I'll be glad.
UPDATED: I changed the "=" problem, but the output still wrong, I printed the output of the function, and it's always zero
The following line has a serious problem:
else if(x = array[middle]) return(1);
Instead of comparing x to array[middle], you are assigning the value of array[middle] to x. Provided this value is nonzero, it will always evaluate to true, and so your function will always return at that point. You should use ==, which compares for equality, instead of =, which means assignment.
This is an extremely common error among beginning C programmers, so you may wonder why A = B is even an expression at all in C, rather than a statement like in Python. The (ex post facto?) rationale is that it is sometimes very convenient to be able to assign a variable inside an expression. Consider:
char *error;
if ((error = do_something()) != NULL) {
printf("error: %s\n", error);
// ...
}
You are using assignment = rather than the test for equality ==. The resulting expression is probably non-zero so the if compares as true.
Ok did u check if u give sorted array as an input to your binary search function? if it is not then using binary search will not give you the correct answer.
I founded the error:
I generate random numbers in a function("random_numbers()"), and the "dim" variable is inside that function, so, the dim inside the main() is 0. so the return value of the search will always be 0. I'm feeling a little bit stupid, but thanks all for the help. Sorry by the newbie error.

(Extreme Noob here) Why wont this C code work?

Why won't this work, I'm very new to programming but I can't seem to figure out why this wont work correctly.
#include <stdio.h>
#include <math.h>
int main(){
int num1;
printf("Enter 1, 2, 3.");
scanf("%d", &num1);
if(num1 = 1)
printf("You entered one");
else if(num1 = 2)
printf("You entered two");
else if(num1 = 3)
printf("You entered three");
else
printf("Invalid");
}
In C it is valid to use assignment (int x = 5) within a conditional (if statement).
For example:
int x = 0;
if (x = 5)
{
}
This will evaluate to true (it returns 5 to the "if" and all non zero terms are true by convention) if the assignment could be done and the value != 0. Which, in this case, it can be done and returns 5.
You were likely looking for this:
int x = 0;
if (x == 5)
{
}
This will evaluate to false (0).
Remember: You use a single equal sign "=" to mean "assignment". Use a double equal sign "==" to mean "comparison".
Replace all the = with == and you should be fine (because = is used for assignment, while == is used to test for equality, which seems to be what you want to do)
In C, as in other many programming languages, the = operator means "assignment". When you do a = 3, that means "assign a with 3", which of course it's something that succeeds and returns true, that's why your program will always enter the first branch.
What you have to do is use the "equality testing" operator, ==, so that a == 3 returns true if and only if the value held by variable a is 3.
Your code having one mistake you have taken = instead of ==, in C = operator means assignment operator while== operator is used for comparision.
To clear about your doubts regarding operators read this link
http://www.tutorialspoint.com/cprogramming/c_operators.htm
And because you started with int main() just for compiler reasons put return 0; at the end of your program to be more correct.
It doesn't work because you need to change the = sign to ==. You use the equal sign sometimes when you declare a int or char. == is meaning equal to and you want to use that when your not declaring ints and chars.While != means not equal.You should also put a return 0; at the end of your program.

assignment works as a condition

Consider the following Code,
int i;
while(i=0)
printf("Hello");
Now Generally speaking i=0 is an assignment and not a condition for while to check.
But the GCC compiler lets it go with a warning and even evaluates it correctly (does not execute the print statement).
Why? I usually would do with parenthesis for the truth value but my juniors feel that I am wrong and there is no real reason for the parenthesis in this!
EDIT: Zeroing down on the 'actual' doubt, Please consider the following test case
int callme(){
return 0;
}
int main(int argc,char*argv[]){
int c;
while(c = callme()){
printf("Calling...\n");
}
return 0;
}
The expression i = 0 does 2 things:
Has the side effect of storing o in i
Yields the value 0
I usually would do with parenthesis for the truth value but my juniors
feel that i am wrong and there is no real reason for the parenthesis
in this
It's usually a hint to the compiler meaning "I actually want this, I didn't forget a =, shut up".
For your specific case there's no reason to write if (i = 0): you already know what if (0) does. But it's pretty useful when used as:
if ((i = some_function()))
...
i=0 is always an assignment (unless you have it as part of int i = 0; where it is an initialization). But any non-void expression may appear inside the condition of a while loop and if it evaluates to non-zero, the body of the loop will be executed, and if it is zero, the body of the loop will not be executed.
The notation:
while (i = 0)
printf("Hello\n");
is always equivalent to:
i = 0;
There is very little justification for writing the loop at all.
People do write other expressions:
while (c = getchar())
...process EOF or a non-null character...
But that's usually a bug. It is more likely that you should be writing:
while ((c = getchar()) != EOF)
...process a character - possibly null...
or even:
while ((c = getchar()) != EOF && c != '\0')
...process a non-null character...
The first getchar() loop gets a warning from GCC; the latter two do not because of the the explicit test of the value from the assignment.
The people who write a condition like this:
while ((c = getchar()))
really annoy me. It avoids the warning from GCC, but it is not (IMNSHO) a good way of coding.
When you use an assignment operator such as
a=0;
You assign the value to 'a', and still return the number 0.
To test your question, I tried these lines of codes:
int a;
printf("%d", a=0);
and these lines displayed 0.
Then, I tested another set of codes:
int b;
printf("%d", b=15);
Here, the lines displayed 15.
So, if you do:
while(a=0)
{
printf("zero");
}
The (a=0) statement would return false, thus not displaying anything.
But if you do:
while(a=15)
{
printf("fifteen");
}
The "fifteen" will be displayed endlessly, because the statement (a=15) will return a non zero value, or 15, which is not false, not zero, thus it is true. :)
As cnicutar has told above the assignment also yields the value zero.
Some additional info:
It is a common coding mistake for people to omit an extra '=' whereby the comparison becomes an assignment.
An easy way to avoid this is to write the comparison as below, in which case even if a '=' is missed compiler will give an error
while(0 == i)
{
prinf("Hello");
}

Resources