C语言学习(3)

版权声明:转载请注明出处:http://blog.csdn.net/liu6886 https://blog.csdn.net/liu6886/article/details/80006088

精度丢失

/*
一个浮点型变量只能保证的有效数字是7位有效数字,后面的数字是无意义的,并不准确地表示该数。
应当避免将一个很大的数和一个很小的数直接相加或相减,否则就会“丢失”小的数。
*/
#include<stdio.h>
#include<stdlib.h>

int main()
{
    float a, b;
    a = 123456.789e5;
    printf("%f\n", a);
    b = a + 20;
    printf("%f\n", b);
    system("pause");
    return 0;
}

算符优先级:

! > 算术运算符 > 关系运算符 > && > || > 条件运算符 > 赋值运算符

1、逻辑运算符

#include <stdio.h>
#include <stdlib.h>
int main()
{
    int year;
    scanf("%d", &year);
    10 == year&&printf("year is 10\n");//逻辑与的短路运算  &&
    10 == year||printf("year is not 10\n");//逻辑或的短路运算  ||
    system("pause");
    return 0;
}

2.条件运算符

#include <stdio.h>
#include <stdlib.h>
int main()
{
    int a, b, c, max1;
    scanf("%d%d%d", &a,&b,&c);
    //c = a > b ? a : b;//找a,b中较大的数赋值给c
    max1 = (a > b ? a : b) > c ? (a > b ? a : b) : c;//找三个数中最大值,条件运算符优先级低,所以要加括号
    printf("a=%d,b=%d,c=%d,max1=%d\n",a,b,c,max1);
    system("pause");
    return 0;
}

位操作符

#include<stdio.h>
#include<stdlib.h>
int main()
{
    short a, b;
    a = 5;
    b = 7;
    //b = ~a;  //按位取反
    printf("%d\n", a&b);  //按位与
    printf("%d\n", a|b);  //按位或
    printf("%d\n", a ^ b);  //按位异或(相同为0,不同为1)   一个数与0异或得本身 与自身异或得0
    int i=1;
    printf("i<<10=%d\n", i << 10);// 2^10=1024
    printf("i=%d\n", i);//左移or右移不会改变变量的值
    a = -6;
    printf("a>>1=%d\n", a >> 1);
    b = -7;
    printf("b>>1=%d\n", b >> 1);//奇数时,负数减一再除2
    system("pause");
    return 0;
}

自增自减运算符

#include <stdio.h>
#include <stdlib.h>
int main()
{
    int a = 10, b;
    //b = a++;//后++  先赋值,后自增。即:b=a,a++
    b = ++a;//前++  先自增,再赋值给b
    printf("a=%d,b=%d\n", a, b);
    system("pause");
    return 0;
}

转义字符

#include<stdio.h>
#include<stdlib.h>
//转义字符
int main()
{
    char c;
    c = '\n';//转义字符,换行,对应enter
    c = '\r';//光标回到行首
    c = '\b';//退格键==删除
    //printf("%c---\n", c);
    //printf("abc\refg\n");
    //printf("\\\\\n");//如果是输出两个反斜杠  需要4个反斜杠
    //printf("abc\bf\n");
    scanf("%c", &c);
    printf("%c\n", c - 32);
    system("pause");
    return 0;
}

猜你喜欢

转载自blog.csdn.net/liu6886/article/details/80006088