c語言可以說是進階計算機語言之母。之前學校有開c語言課程,但是幾乎沒有聽過。期末考也是突擊兩小時。寫java也有一年多了,總感覺隻是停在用的基礎上,沒有辦法去深究它到底是怎麼樣組織資料的。是以在一直想重新來一遍C語言。這算是一個開始。
# include <stdio.h>
int main()
{
float weight;
float value;
printf("Are you worth your weight in platinum? \n");
printf("Let's check it out.\n");
printf("Please enter your weight in pounds: ");
//scanf() 方法用于讀取鍵盤的輸入, %f 表明要讀取的是浮點數, &weight表示 把scanf()方法讀取的浮點數指派給 weight。
scanf("%f", &weight);
value = 1700.0 * weight * 14.5833;
//在printf() 方法中,使用 %f 來輸出浮點數。%.2f 用于精确控制輸出,隻輸出小數點後兩位
printf("Your weight in platinum is worth $%.2f.\n", value);
printf("You are easily worth that ! If platinum price drop,\n");
printf("eat more to maintain your value.\n");
}
輸出
C語言資料類型關鍵字
記憶體:
位:bit 最小的存儲機關,可以存儲0或1.位是計算機記憶體的基本建構塊;
位元組: byte 對于幾乎所有的機器,1位元組均為8位,這是位元組的标準定義。有2^8種組合
字: word 設計計算機時給定的自然 存儲機關,對于8位的微型計算機,1個字長隻有8位。 現在個人計算機增至16位,32位,64位。計算機的字長越大,其資料轉移越快,允許的記憶體通路也越多。
整數存儲結構
浮點數存儲結構:
資料類型
1. int(整型):
int的大小為一個字長,而字長取決于計算機的設定。我現在的計算機是64位的,是以我這裡一個int的大小為64位,也就是8個byte。但是我下面用sizeof(int) = 4, sizeof(int*)=8這就很尴尬了。
//聲明
int age; //聲明一個
int count, amount, plat; //聲明多個
//初始化
int age = 12; //聲明時初始化
int count;
count = 5; //先聲明,後進行初始化
int dogs = 23, cats = 24; //聲明多個并初始化
int dogs, cats = 55; //正确,但不推薦。格式糟糕
/*
聲明時為變量進行記憶體配置設定,初始化時為變量指派
*/
#include <stdio.h>
int main()
{
int ten = 10;
int two = 2;
printf("正确列印方式:\n");
printf("%d 減去 %d 等于 %d\n", ten, two, ten - two);
printf("錯誤方式:\n");
printf("%d 減去 %d 等于 %d\n", ten); //遺漏2個參數
return 0;
}
顯示進制輸出
#include<stdio.h>
int main()
{
int x = 100;
printf("一個整型的大小為%d\n",sizeof(int));
printf("一個整型指針的大小為%d\n",sizeof(int*));
printf("dec =%d; octal = %o; hex = %x\n", x, x, x);
printf("dec =%d; octal = %#o; hex = %#x\n", x, x, x);
return 0;
}
/*
output:
一個整型的大小為4
一個整型指針的大小為8
dec =100; octal = 144; hex = 64
dec =100; octal = 0144; hex = 0x64
*/
其他整型
1. short int 或 short: 占用的空間可能比int小
2. long int 或long : 占用的空間可能比int大
3. long long int 或 long long : 占用的空間可能比long大,至少為64位
4. unsigned 無符号
5. 為什麼說 short i可能比 int 小。因為隻規定了short占用的空間不能大于int,int占用的空間不能大于long.。是以它們有可能是相等的
整數溢出:
#include<stdio.h>
int main()
{
int x = 2147483647;
unsigned int y = 4294967295;
printf("%d; %d; %d\n", x, x+1, x+2);
printf("%d; %d; %d\n", y, y+1, y+2);
return 0;
}
/*
output:
2147483647; -2147483648; -2147483647
-1; 0; 1
*/