第2章 數(shù)據(jù)類型與操作符
- 使用
#define
比const
的好處是常量不占用內(nèi)存 -
volatitle
表示該變量值在任意時(shí)刻可能被外部進(jìn)程更改 -
++
前置和後置的區(qū)別是加1操作執(zhí)行的時(shí)機(jī) - 可以用
<=
胆萧、>=
這種關(guān)系運(yùn)算符 - c語(yǔ)言內(nèi)部锰茉,用0表示false,其他任何值都會(huì)被當(dāng)作true來處理
- 十進(jìn)制轉(zhuǎn)二進(jìn)制:
對(duì)應(yīng)正數(shù)二進(jìn)制 -> 取反 -> +1
- 異或操作真值表
x | y | x^y |
---|---|---|
0 | 0 | 0 |
0 | 1 | 1 |
1 | 0 | 1 |
1 | 1 | 0 |
以上同時(shí)演示了左對(duì)齊、右對(duì)齊捞奕、居中對(duì)齊三種方式
- 左移操作符
<<
直接丟掉左邊削祈,右邊補(bǔ)零拾碌;右移操作符>>
丟掉右邊卦绣,如果是負(fù)數(shù)左邊還是保持符號(hào)位為1
第三章 c語(yǔ)言中的控制語(yǔ)句
- 求二次方程的根
#include<stdio.h>
#include<math.h>
/*
d=b^2-4ac;
1.d>0
x1=(-b+sqrt(d))/2a; x2=(-b-sqrt(d))/2a;
2.d=0;
x1=x2=-b/2a;
3.d<0;
根為r+r1j和r-r1j
r=-b/2a; r1=sqrt(d)/2a;
*/
int main()
{
int a,b, c;
double x1, x2, r, r1;
long d;
printf("input a b c:");
scanf_s("%d %d %d", &a, &b, &c);
//計(jì)算判別式
d = b * b - 4 * a * c;
if (d > 0)
{
printf("roots are unequal and real\n");
int k=a*2;
x1 = (-b + sqrt(d)) / (k);
x2 = (-b - sqrt(d)) / (k);
printf("root1 = %.2f, root2 = %.2f\n", x1,x2);
}
else if (d == 0)
{
printf("roots are equal and real\n");
x1 = (-b) / (a * 2);
printf("root1 = %.2f\n", x1);
}
else
{
printf("roots are complex\n");
d = -d;
r = -b / (2*a);
int k=a*2;
r1 = sqrt(d) / (k);
printf("root1 = %.2f+%.2fi, root2 = %.2f-%.2fi\n", r, r1, r, r1);
}
return 0;
}
- 計(jì)算一個(gè)整數(shù)中各位數(shù)字之和
#include<stdio.h>
#include<math.h>
/*
用%10取最後一位數(shù)字,用/移除最后一位數(shù)字
*/
int main()
{
int num, digit, sum = 0;
printf("input a num:");
scanf_s("%d", &num);
do
{
digit = num % 10;
sum += digit;
num /= 10;
} while (num > 0);
printf("sum of digits = %d\n", sum);
return 0;
}
- while循環(huán)比do-while循環(huán)更高效?不能這么說吧缩擂?
- 斐波那契數(shù)列
#include<stdio.h>
#include<math.h>
/*
生成斐波那契數(shù)列
*/
int main()
{
int i, n, cnt;
long unsigned int f1, f2, f;
printf("how many Fibonaccis you want: ");
scanf_s("%d", &n);
/*
斐波那契數(shù)列的前兩項(xiàng)是0和1
*/
f1 = 0;
f2 = 1;
if (n == 1)printf("%lu\n", f1);
else
{
if (n == 2)
{
printf("%lu\t%lu\n", f1, f2);
}
else
{
cnt = 2;
printf("%lu\t%lu\t", f1, f2);
for (i = 3; i <= n; i++)
{
f = f1 + f2;
printf("%d", f);
cnt++;
if (cnt % 5 != 0)
{
printf("\t");
}
else
{
printf("\n");
}
f1 = f2;
f2 = f;
}
}
}
return 0;
}
- switch變量只能用整型或者字符類型
- exit(0)代表程序正常終止鼠冕,exit(1)代表程序非正常終止
- break直接跳出當(dāng)前代碼塊,而continue終止當(dāng)前循環(huán)胯盯,回到下一個(gè)循環(huán)開始