前往
大廳
主題

[OJ練習] 10812、11044 嘗試多練習 malloc

テリ君(福佬模式) | 2022-12-08 11:41:32 | 巴幣 4 | 人氣 182

10812(1/5)

#include <stdio.h>
#include <stdlib.h>

int main(){
    int n;
    int *s, *d;
    int temp_s, temp_d;
    scanf("%d", &n);
    
    s = (int *)malloc(sizeof(int) * n);
    d = (int *)malloc(sizeof(int) * n);
    
    for(int i = 0; i < n; i++){
        scanf("%d %d", s + i, d + i);
    }
    for(int i = 0; i < n; i++){
        for(int j = 0; j < *(s + i); j++){
            temp_s = *(s + i) - j;
            temp_d = j;
            if(temp_s - temp_d == *(d + i)){
                printf("%d %d\n", temp_s, temp_d);
                break;
            }
            else if(temp_s - temp_d < *(d + i)){
                printf("impossible\n");
                break;
            }
        }
    }
    
    return 0;
}

11044(1/5)

#include <stdio.h>
#include <stdlib.h>
#include <math.h>

int main(){
    int t, check = 0;
    scanf("%d", &t);
    int *n, *m, *result;
    
    n = (int *)malloc(sizeof(int) * t);
    m = (int *)malloc(sizeof(int) * t);
    result = (int *)malloc(sizeof(int) * t);
    
    for(int i = 0; i < t; i++){
        scanf("%d %d", n + i, m + i);
        if(*(n + i) < 6 || *(n + i) > 10000 || *(m + i) < 6 || *(m + i) > 10000){
            check = 1;
            break;
        }
    }
    
    if(check == 0){
        for(int i = 0; i < t; i++){
            result = (*(n + i) / 3) * (*(m + i) / 3);
            printf("%d\n", result);
        }
    }
    
    return 0;
}

這兩題想說我就不先訂製陣列大小,直接用指標和malloc去做,順便練習指標的應用,
不過像上次有個二維陣列題目,我還沒學會怎麼用malloc去騰出空間。
整體不難,就只是說想要用不同方法去呈現和練習。

阿對,10812記得如果有output就要break,不然會印兩次= =

同日更: 我忘記free()了,以後要記得,就跟關檔案一樣。

創作回應

更多創作