flag_shop
考點
- C 語言 int over flow 範圍
- 二的補數
如何解題
這題還滿好玩的, 要買東西但是初始的錢不夠,選項又都是讓你花錢,除了買 flag 之外,還可以買不是 flag 的東西,它會算出讀入一個 int 算出花費,再拿原本的錢去扣,但數量不能是負的,學過小說二年級數學的肯定會知道,可以讓 total_cost = 900*number_flags
乘上 900 後是一筆很大的負數,這樣就會找到財富密碼,int32 範圍是-2^32~2^32-1 也就是-2147483648 到 2147483647,原本有 110 塊錢,不能讓乘上 900 之後的那個大數字加完讓最後口袋的錢變成負的,計算 (2**31 - 1 - 1100 + 100000) // 900 就是可以填入讓程式最後計算結果會溢位的數字。在門檻附近的幾個數字也都可以因為 *900 之後進位都足夠大。
else if(menu == 2){
printf("Currently for sale\n");
printf("1. Defintely not the flag Flag\n");
printf("2. 1337 Flag\n");
int auction_choice;
fflush(stdin);
scanf("%d", &auction_choice);
if(auction_choice == 1){
printf("These knockoff Flags cost 900 each, enter desired quantity\n");
int number_flags = 0;
fflush(stdin);
scanf("%d", &number_flags);
if(number_flags > 0){
int total_cost = 0;
total_cost = 900*number_flags;
printf("\nThe final cost is: %d\n", total_cost);
if(total_cost <= account_balance){
account_balance = account_balance - total_cost;
printf("\nYour current balance after transaction: %d\n\n", account_balance);
}
else{
printf("Not enough funds to complete purchase\n");
}
}