我必須創建一個函式,給定 2 個不同的值 s1 和 s2 (s1<s2) 以及由檔案填充的向量,創建一個新向量并排列第一個向量的值 (a),將 a<s1 元素放在新向量的開始,然后是值 s1< a < s2,最后是值 a>s2 并列印初始向量和新向量
#include <stdio.h>
#include <stdlib.h>
#define DIM 11
void printVect(double *);
double *functB(double *vectPtr);
int main()
{
FILE *fp;
double vect[DIM], *Ptr;
double newvect[DIM], *nvPtr;
Ptr=(double*) malloc(sizeof(double)*DIM);
fp=fopen("dati.txt", "r");
for(int i=0; i<DIM; i )
{
fscanf(fp, "%lf", &Ptr[i]);
}
printVect(Ptr);
puts("\n");
*newvect=*functB(Ptr);
printVect(newvect);
}
void printVect(double *vector)
{
for(int i=0; i<DIM; i )
{
printf(".2lf", vector[i]);
}
}
double *functB(double *vectPtr)
{
int s1=2; int s2=5; int n=0;
double *newVect;
for(int i=0; i<DIM; i )
{
if(vectPtr[i]<s1)
{
newVect[n]=vectPtr[i];
n ;
}
}
for(int i=0; i<DIM; i )
{
if(vectPtr[i]<s2 && vectPtr[i]>s1)
{
newVect[n]=vectPtr[i];
n ;
}
}
for(int i=0; i<DIM; i )
{
if(vectPtr[i]>s2)
{
newVect[n]=vectPtr[i];
n ;
}
}
return newVect;
}
我得到的輸出是
10.00 2.30 4.56 2.00 1.23 8.65 10.00 -12.30 4.34 16.22 2.30
所以程式只列印第一個向量并在之后停止作業
printVect(Ptr);
puts("\n");
我想問題出在functB函式上,但我不知道問題出在哪里
uj5u.com熱心網友回復:
在functB中,您回傳并改變newVect已定義但未初始化的。
double *newVect = malloc (DIM*sizeof(double));
if (!newVect) generate_error_and_return();
else your code.
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/427886.html
上一篇:信號6的問題
下一篇:檢查單詞中是否出現字母
