您的位置:首页 > 新闻 > 热点要闻 > C语言循环中获取之前变量的值

C语言循环中获取之前变量的值

2024/10/12 3:09:04 来源:https://blog.csdn.net/weixin_57097753/article/details/139870868  浏览:    关键词:C语言循环中获取之前变量的值

获取上个数组变量的值

#include <stdio.h>
#include <string.h>enum { GG, DD };
int main() {int bi[] = {0, 0};int bi_s1[] = {0, 0};for (int i = 0; i < 5; i++) {memcpy(bi_s1, bi, sizeof(bi));bi[GG] = i * 3;bi[DD] = i * 2;printf("bigg = %d, bigg_s1 = %d\n", bi[GG], bi_s1[GG]);}return 0;
}

如果不想用memcpy进行拷贝赋值,可以使用一个额外的变量来存储上一次迭代的数组的索引,利用这个索引交替访问两个数组。

#include <stdio.h>enum { GG, DD };
int main() {int bi[2][2] = {{0, 0}, {0, 0}};int current = 0; // 当前正在使用的数组索引for (int i = 0; i < 5; i++) {int previous = (current + 1) % 2; // 计算上一个数组的索引// 更新当前数组的值bi[current][GG] = i * 3;bi[current][DD] = i * 2;// 输出当前数组和上一个数组的内容printf("bigg = %d, bigg_s1 = %d\n", bi[current][GG], bi[previous][GG]);// 切换到下一个数组current = previous;}return 0;
}

在这个实现中,我们使用了一个二维数组bi[2][2],其中bi[0]bi[1]分别表示两个数组。current变量用于指示当前正在使用的数组的索引,而previous变量则计算上一个数组的索引,以便在打印时使用。

输出结果将显示每次迭代中当前数组的值和上一次迭代中的数组的值,效果类似于使用memcpy复制数组的情况,但避免了内存复制的开销。

这种方法更高效,因为它只使用了一个额外的整数变量来存储索引,而不需要进行数组内容的复制。

经测试,性能可以快5倍左右。

获取更前面的数组的值

#include <stdio.h>enum { GG, DD };
int main() {int bi[4][2] = {{0, 0}, {0, 0}, {0, 0}, {0, 0}};int current = 0;int s1, s2, s3;for (int i = 1; i <= 10; i++) {s1 = (current + 1) % 4; // 上个值的索引 索引%元素数量 实现循环索引s2 = (current + 2) % 4; // 上上个值的索引s3 = (current + 3) % 4; // 上上上个值的索引bi[current][GG] = i * 3;bi[current][DD] = i * 2;printf("%d %d %d %d \n", current, s1, s2, s3);printf("s = %d, s1 = %d, s2 = %d s3 = %d \n\n", bi[current][GG], bi[s1][GG], bi[s2][GG], bi[s3][GG]);current = s3; // 把最后一个赋值给current}return 0;
}

如果有多个数组 即使其中一个数组用不到s4,s5 也必须保持结构相同。
这样就不用为每个数组去计算位置,只要知道最大那个数组的大小即可,提高性能。

#include <stdio.h>
#define SMAX 6 // 最多只能保存6组数据,当前1个,往前推5个。enum { GG, DD };
int main() {// 如果有多个数组 即使其中一个数组用不到s4,s5 也必须保持结构相同int bi[SMAX][2] = {{0, 0}, {0, 0}, {0, 0}, {0, 0}, {0, 0}, {0, 0}};int di[SMAX][2] = {{0, 0}, {0, 0}, {0, 0}, {0, 0}, {0, 0}, {0, 0}};int s0 = 0;int s1, s2, s3, s4, s5;for (int i = 1; i <= 10; i++) {s1 = (s0 + 1) % SMAX;s2 = (s0 + 2) % SMAX;s3 = (s0 + 3) % SMAX;s4 = (s0 + 4) % SMAX;s5 = (s0 + 5) % SMAX; // 虽多只能到s5bi[s0][GG] = i * 3;bi[s0][DD] = i * 2;di[s0][GG] = i + 5;di[s0][DD] = i + 3;printf("%d %d %d %d %d %d \n", s0, s1, s2, s3, s4, s5);printf("s = %d, s1 = %d, s2 = %d s3 = %d \n", bi[s0][GG], bi[s1][GG], bi[s2][GG], bi[s3][GG]);printf("s = %d, s1 = %d\n\n", di[s0][GG], di[s1][GG]);s0 = s5; // 最后一个赋值给s0}return 0;
}

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com