lab2
#include <ctype.h> #include <cs50.h> #include <stdio.h> #include <string.h> // Points assigned to each letter of the alphabet int POINTS[] = {1, 3, 3, 2, 1, 4, 2, 4, 1, 8, 5, 1, 3, 1, 1, 3, 10, 1, 1, 1, 1, 4, 4, 8, 4, 10}; int compute_score(string word); int main(void) { // Get input words from both players string word1 = get_string("Player 1: "); string word2 = get_string("Player 2: "); // Score both words int score1 = compute_score(word1); int score2 = compute_score(word2); // TODO: Print the winner if(score1 > score2){ printf("player 1 wins!\n"); } else if(score1 == score2){ printf("both win!\n"); }else{ printf("player 2 wins!\n"); } } int compute_score(string word) { int n = strlen(word); int score = 0; int flag = 0; for(int i=0;i<n;i++){ if(word[i]>64 && word[i]<91){ flag = (int)(word[i]-65); } else if(word[i]>96 && word[i]<123){ flag = (int)(word[i]-97); } else{ printf("please check the input!\n"); } score += POINTS[flag]; } return score; // TODO: Compute and return score for string }
problem set2
(1) 切记,幂不要写成2^j这样...
#include <cs50.h> #include <stdio.h> #include <string.h> #include <math.h> const int BITS_IN_BYTE = 8; void print_bulb(int bit); int main(void) { // TODO string message = get_string("Message: "); int n = strlen(message); int number = 0; int flag = 0; for(int i=0;i<n;i++){ number = (int)message[i]; //printf("number:%i\n",number); int bit = 0; for(int j=7;j>=0;j--){ flag = pow(2,j); // printf("flag:%i-%i",j,flag); if(number<flag){ bit = 0; } else{ bit = 1; number -= flag; } //printf("%i",bit); print_bulb(bit); } printf("\n"); } } void print_bulb(int bit) { if (bit == 0) { // Dark emoji printf("\U000026AB"); } else if (bit == 1) { // Light emoji printf("\U0001F7E1"); } }
(2)
#include <cs50.h> #include <stdio.h> #include <string.h> #include <stdlib.h> #include <ctype.h> int main(int argc, string argv[]) { int k = atoi(argv[1]); if(argc != 2 || k<0 || k>126){ printf("Usage: ./caesar key\n"); return 1; } string check_input = argv[1]; int m = strlen(check_input); int flag = 0; for(int i=0;i<m;i++){ if(isdigit(check_input[i])){ continue; } flag++; } if(flag == 0){ string text = get_string("plaintext: "); int n = strlen(text); printf("ciphertext:"); for(int i=0;i<n;i++){ if(isalpha(text[i])){ if(isupper(text[i])){ printf("%c",(text[i] - 65 + k) % 26 + 65); } else{ printf("%c",(text[i] - 97 + k) % 26 + 97); } } else{ printf("%c",text[i]); } } printf("\n"); return 0; } printf("Usage: ./caesar key\n"); return 1; }