gpt4 book ai didi

c - 如何为排序 vector 创建循环

转载 作者:太空宇宙 更新时间:2023-11-03 23:57:52 25 4
gpt4 key购买 nike

我有一个家庭作业问题要求我的代码读取一个 10 长度的 vector ,按升序排列它然后打印它。我正在尝试使用变量 int k 作为可数索引来执行此操作,其中代码验证 vector 中的特定位置是否大于其他位置,并为每个较小的变量将 1 添加到 k。然后,我创建了第二个 vector ,并为其第 k 个位置指定了第一个 vector 的值。汇编没有指出任何错误。代码运行,我通知 vector 的 10 个值,然后它返回一个大数字并崩溃。谁能帮帮我?提前致谢。

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

int main ()
{
setlocale(LC_ALL, "Portuguese");
//creates two double vectors
double v[10], w[10];
//creates a int variable to be a countable index
int k = 0;
//asks for the user to inform the values of the vector
for (int i=0; i<=9; i++)
{
printf("Digite um número:\n");
scanf("%lf", &v[i]);
}
//Here, I create this loop to verify whether each position of the vector v is greater than the other positions.
for (int j=9; j>=0; j--)
{
//For the case j=9, I verify if it is greater than all the predecessor values, and add 1 to k for each case
if (j==9)
{
for (int t=j-1; t>=0; t--)
{
if (v[j]>v[t])
{
k+=1;
}
}
//I attribute this value of v to the kth position of the new vector, and restart the countable index
w[k]=v[j];
k=0;
continue;
}
//I do the same for the case in which j=0, verifying whether it is greater than the subsequent values
else if (j==0)
{
for (int s=j+1; s<=9; s++)
{
if (v[j]>v[s])
{
k+=1;
}
}
w[k]=v[j];
k=0;
continue;
}
//For all the other values of the vector, I test both whether they are greater than the
//predecessors and the subsequent values, and add 1 to k for each case
else
{
for (int t=j-1; t>=0; t--)
{
if (v[j]>v[t])
{
k+=1;
}
}
for (int s=j+1; s<=9; s--)
{
if (v[j]>v[s])
{
k+=1;
}
}
//I attribute this value to the kth position of the new vector and restart the countable index
w[k]=v[j];
k=0;

}
//Here my loop ends
}
//I print the new vector
for (int p=0; p<=9; p++)
{
printf(" %lf ",w[p]);
}
system("pause");
return 0;
}

最佳答案

for (int s=j+1; s<=9; s--)应该有 s++ .我没有看到任何其他错误,但我会检查 gdb如果那不能解决问题。

关于c - 如何为排序 vector 创建循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58160255/

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