首页 > 解决方案 > 调用文件时 C 中的向量操作

问题描述

我们被要求做以下事情;但是,我是编码新手,几乎没有遇到什么困难。我在下面附上了我的代码,它引发了多个错误。有人可以帮忙吗?

描述 - - - - - - - - - - - - - - - - - - - - - - - - - ------------

编写一个名为“VectorOperations”的 C 函数,它

  1. 将一个名为“size”的整数作为输入,它指定了两个浮点数组的大小。如果大小无效,则打印“Invalid Size”,否则执行以下步骤。

  2. 从名为“vectors.txt”的输入文件中读取两个数组,该文件位于当前目录(您的 C 文件所在的位置)。输入文件的格式必须如下(每一行代表一个数组,每个数组成员之间用一个空格分隔):

0.75 0.95 0.98 0.88 0.51

0.91 0.43 0.56 1.02 1.03

  1. 计算两个数组(向量)的点积。

  2. 计算两个数组的最大值(两个数组成员中最大的成员)。

  3. 将点积和最大值写入名为“results.txt”的文件中,如下所示(请严格遵循输出格式;每个分隔行有 40 个“-”字符。数字也正好有 2 个小数位):

以这种形式打印-->

运算:点积和最大值


这是我的代码。

#include <stdio.h>
int vectors;
int main ()
{
int readFile(void){
    FILE *VectorOperations;        /* a file stream variable */
    char fileName[] = "vectors.txt"; /* a c-string */
    char chunk[100];
    vectors = fopen(fileName, "r" ); // open for reading and writing, overwriting a file
    if(vectors == NULL ) /*check for file open errors*/
    {
        printf("Invalid Size");
        return -1;  /* terminate the program */
    }
    else
    {
         /* write data to the file */
        for(int i=0; i<40; i++) fprintf(VectorOperations, "-");
        fprintf(VectorOperations, "\nSUM %s\n");
        for(int i=0; i<40; i++) fprintf(VectorOperations, "-");
        fgets(chunk, sizeof(chunk), vectors);
        fgets(chunk, sizeof(chunk), vectors);
        fgets(chunk, sizeof(chunk), vectors);
        fgets(chunk, sizeof(chunk), vectors);
        printf("%s", chunk);

        fclose(VectorOperations);    /* close the file stream */
        return 0;
}
// ---------------------------------------------------------
int Tutorial4_run(void){
    writeFile();
    readFile();
    printf("\n");
    return 0;
}



int writeFile(){
    FILE *VectorOperations;        /* a file stream variable */
    
    char fileName[] = "vectors.txt"; /* a c-string */
    char size[] = "size";       /* a c-string */
    VectorOperations = fopen(fileName, "w" ); // open for writing, overwriting a file
    if(VectorOperations == NULL ) /*check for file open errors*/
    {
        fprintf("Invalid Size");
        return -1;  /* terminate the program */
    }
    else
    {
        /* write data to the file */
        for(int i=0; i<40; i++) fprintf(VectorOperations, "-");
        fprintf(VectorOperations, "\nsize %s\n", size);
        for(int i=0; i<40; i++) fprintf(VectorOperations, "-");
        fgets(chunk, sizeof(chunk), vectors);
        fgets(chunk, sizeof(chunk), vectors);
        fgets(chunk, sizeof(chunk), vectors);
        fgets(chunk, sizeof(chunk), vectors);
        printf("%s", chunk);

        fclose(VectorOperations);    /* close the file stream */
        return 0;
    }
}

}

标签: arraysc

解决方案


推荐阅读