Is-1/2 defined in C language?

Source: Internet
Author: User

I can see that a netizen's signature says "-1/2 in C language is not defined". No matter what it means, I wrote a few lines of code to test it with curiosity. I hope you will not laugh at it. It should be said that the code is like this.
# Include <stdio. h>

Void main (){
Float a =-1/2;
Printf ("% s % f", a <0? "This is-": "this is +", );
Return;
}
I used a judgment to verify positive and negative values. On the surface, it seems that the Code has no problem, but you can see the problem after carefully reading the code or executing the following statements. The result is "0". Why? Let's take a look at float a =-1/2. float a can definitely represent a negative number and a decimal point, but what about-1/2? This is a number, but it represents an integer data. The operation result of the Two integer data is still an integer, equivalent to the code float a = (int) (-1/2 ), -1/2 the result is 0 (0 is positive or negative), and the result is this is + 0. Therefore, this problem has been explained in c. If you want to get the desired result, the code should be as follows:
# Include <stdio. h>

Void main (){
Float a = (float)-1/(float) 2;
Printf ("% s % f", a <0? "This is-": "this is +", );
Return;
}
Use the mandatory conversion of c to convert-1 and 2 to float. The result is float. The final result at this time is this is--0.5000. Flash.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.