arrays - 调用文件时 C 中的向量操作
问题描述
我们被要求做以下事情;但是,我是编码新手,几乎没有遇到什么困难。我在下面附上了我的代码,它引发了多个错误。有人可以帮忙吗?
描述 - - - - - - - - - - - - - - - - - - - - - - - - - ------------
编写一个名为“VectorOperations”的 C 函数,它
将一个名为“size”的整数作为输入,它指定了两个浮点数组的大小。如果大小无效,则打印“Invalid Size”,否则执行以下步骤。
从名为“vectors.txt”的输入文件中读取两个数组,该文件位于当前目录(您的 C 文件所在的位置)。输入文件的格式必须如下(每一行代表一个数组,每个数组成员之间用一个空格分隔):
0.75 0.95 0.98 0.88 0.51
0.91 0.43 0.56 1.02 1.03
计算两个数组(向量)的点积。
计算两个数组的最大值(两个数组成员中最大的成员)。
将点积和最大值写入名为“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;
}
}
}
解决方案
推荐阅读
- python - 如何在 RedHat 上安装 tkinter?
- linux - Raspberry Pi 配置 - 从单独的文件中读取参数
- django - 类通用 DeleteView 不适用于与模型相关的模型
- git - 仅当存在拖车时才在拖车和 %s 之间添加空格
- catboost - catboost 特征图中的“不同特征值的预测”曲线是什么?
- javascript - 为什么数字属性访问速度要慢 100 倍?
- python - FPDF - 如何在 Python 中逐行对齐
- python - 未能在发现服务中执行刷新元数据课程
- roku - 允许 Roku 频道的自定义节目徽标和背景图片
- javascript - 在 ag-grid 过滤器中允许空格