C语言-找出数组中两个数字的和为该数字的位置

1.题目要求

复制代码
(语言: C)给定一组整形数组和一个数字,找出数组中两个数字的和为该数字的位置,例如
数组{2, 7, 11, 15}, 数字9,输出为1,2

函数原型为:
int *twoSum(int numbers[], int n, int target) 
//函数中定义一个动态数组,用于存储这两个数字的下标,最后返回动态数组的首地址。
//不要忘了在主函数中要释放动态数组占用的内存。

输入输出格式为
printf("Please input the array size\n");
scanf("%d");
for()
 {
        printf("Please input the %d-th number\n",i);
        scanf("%d");
 }
    printf("Please input the target number\n");
    scanf("%d");
    if (存在)
    {
        printf("The index1: %d; the index2: %d\n");
        printf("values are %d and %d.\n");
    }else
    {
        printf("result is not available!\n");
    }

程序运行如下
Please input the array size
3
Please input the 0-th number
1
Please input the 1-th number
2
Please input the 2-th number
3
Please input the target number
3
The index1: 1; the index2: 2
values are 1 and 2.

2.代码实现

cpp 复制代码
#include <stdio.h>
#include <stdlib.h>

int *twoSum(int numbers[], int n, int target) {
    int *result = (int *)malloc(2 * sizeof(int));
    for (int i = 0; i < n - 1; i++) {
        for (int j = i + 1; j < n; j++) {
            if (numbers[i] + numbers[j] == target) {
                result[0] = i;
                result[1] = j;
                return result;
            }
        }
    }
    free(result);
    return NULL;
}

int main() {
    int n;
    printf("Please input the array size\n");
    scanf("%d", &n);

    int *numbers = (int *)malloc(n * sizeof(int));
    for (int i = 0; i < n; i++) {
        printf("Please input the %d -th number\n", i);
        scanf("%d", &numbers[i]);
    }

    int target;
    printf("Please input the target number\n");
    scanf("%d", &target);

    int *result = twoSum(numbers, n, target);
    if (result) {
        printf("The index1: %d; the index2: %d\n", result[0], result[1]);
        printf("values are %d and %d.\n", numbers[result[0]], numbers[result[1]]);
        free(result);
    } else {
        printf("result is not available!\n");
    }

    free(numbers);
    return 0;
}
相关推荐
xxie1237941 小时前
return与print
开发语言·python
秋91 小时前
从 Python 后端工程师转型 AI Engineer(AI 工程化)的完整补课清单(2026实战版)
开发语言·人工智能·python
程序员二叉2 小时前
【Java】 异常高频面试题精讲 | 易错点+对比总结
java·开发语言·面试
玖玥拾2 小时前
C/C++ 基础笔记(十四)多态与模板编程
c语言·c++·多态·模板
慕木沐2 小时前
Google ADK Java 1.0版本 核心机制与实战 Demo
java·开发语言·python
Roann_seo%3 小时前
C++文件操作完全指南:从文本读写到二进制文件处理
开发语言·c++
huangdong_4 小时前
淘宝商品SKU图自动分类技术深度解析:从DOM解析到智能归档
开发语言·javascript·ecmascript
阿正的梦工坊4 小时前
【Rust】12-借用检查器与非词法生命周期
开发语言·后端·rust
qq_2518364574 小时前
基于java Web网络订餐系统设计与实现 源码文档
java·开发语言·前端
秋94 小时前
3年经验Python后端转AI Engineer:3个月实战转型计划(2026版)
开发语言·人工智能·python