HackerRank - C语言 - Introduction - Pointers in C

本文详细介绍了如何在C语言中使用指针来更新两个整数的总和和绝对差,提供了两种实现方法:一种是使用条件语句,另一种是使用三目条件运算符,帮助读者深入理解指针操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Pointers in C

任务

完成函数void update(int *a,int *b),该函数读取两个整数作为参数,并设置它们的总和为a以及它们的绝对差b

解答

使用条件语句

#include <stdio.h>

void update(int *a,int *b) {
    // Complete this function  
    int temp;  
    temp = *a;
    *a = *a + *b;
    if(temp>*b){
        *b = temp - *b;
    }
    else{
        *b = *b - temp;
    }
}

int main() {
    int a, b;
    int *pa = &a, *pb = &b;
    
    scanf("%d %d", &a, &b);
    update(pa, pb);
    printf("%d\n%d", a, b);

    return 0;
}


使用三目条件运算符

#include <stdio.h>

void update(int *a,int *b) {
    *a = *a + *b;
    *b = *a - 2 * (*b)> 0 ? *a - 2 * (*b) : 2 * (*b) - *a;
}

int main() {
    int a, b;
    int *pa = &a, *pb = &b;
    
    scanf("%d %d", &a, &b);
    update(pa, pb);
    printf("%d\n%d", a, b);

    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值