gpt4 book ai didi

Python 到 C for 循环转换

转载 作者:行者123 更新时间:2023-11-30 18:31:11 25 4
gpt4 key购买 nike

我有以下 python 代码:

r = range(1,10)
r_squared = []

for item in r:
print item
r_squared.append(item*item)

如何将此代码转换为 C 语言? C 中有类似可变数组的东西吗?或者我该如何做相当于 python 追加的事情?

最佳答案

c 中的简单数组。C 中的数组是同质

int arr[10];
int i = 0;
for(i=0;i<sizeof(arr);i++)
{
arr[i] = i; // Initializing each element seperately
}

尝试在 C 中使用 vector 来完成这个 link

/ vector-usage.c

#include <stdio.h>
#include "vector.h"

int main() {
// declare and initialize a new vector
Vector vector;
vector_init(&vector);

// fill it up with 150 arbitrary values
// this should expand capacity up to 200
int i;
for (i = 200; i > -50; i--) {
vector_append(&vector, i);
}

// set a value at an arbitrary index
// this will expand and zero-fill the vector to fit
vector_set(&vector, 4452, 21312984);

// print out an arbitrary value in the vector
printf("Heres the value at 27: %d\n", vector_get(&vector, 27));

// we're all done playing with our vector,
// so free its underlying data array
vector_free(&vector);
}

关于Python 到 C for 循环转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25779274/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com