c - 如何用新值覆盖用户输入的向量的分量?
问题描述
刚开始学习 C,如果您能帮助我解决以下问题,那就太好了:
我刚刚编写了一个程序,该程序保存用户输入的 4 分量向量(使用调用函数save_vector
),打印它(使用调用函数print_vector
),如果任何分量为负数,它也会使用绝对值(正数)的所有分量打印它功能absolute_values
。
现在我只想使用具有绝对值的向量。如何将新的绝对值保存到同一个向量中并覆盖用户输入的绝对值?
期待阅读任何改进这段代码的建议!谢谢!:-)
#include <stdio.h>
void print_vector(int N,float * V);
void save_vector(int N,float * V);
void absolute_values(int N, float * V);
int main(void)
{
const int n=5;
int i;
float v[n];
puts("Enter the 5 components of the vector:");
save_vector(n, v);
puts("\nThe vector is:");
print_vector(n, v);
puts("\nThe absolute vector is:");
absolute_values(n, v);
return 0;
}
void save_vector(int N, float * V)
{
int i;
for(i=0;i<N;i++)
scanf("%f",V+i);
}
void print_vector(int N, float * V)
{
int i;
for(i=0;i<N;i++)
printf(" %.2f ",*(V+i));
}
void absolute_values(int N, float * V)
{
int i;
for(i=0;i<N;i++)
{
printf(" %.2f ", ((V[i]<0)?-V[i]:V[i]));
}
}
解决方案
在查看评论部分并遵循@Some程序员花花公子的建议后,将最终答案留在这里!:-)
void print_vector(int N,float * V);
void save_vector(int N,float * V);
void absolute_values(int N, float * V);
int main(void)
{
const int n=5;
int i;
float v[n];
puts("Enter the 5 components of the vector:");
save_vector(n, v);
puts("\nThe vector is:");
print_vector(n, v);
puts("\nThe absolute vector is:");
absolute_values(n, v);
return 0;
}
void save_vector(int N, float * V)
{
int i;
for(i=0;i<N;i++)
scanf("%f",V+i);
}
void print_vector(int N, float * V)
{
int i;
for(i=0;i<N;i++)
printf(" %.2f ",*(V+i));
}
void absolute_values(int N, float * V)
{
int i;
for(i=0;i<N;i++)
{
V[i]=((V[i]<0)?-V[i]:V[i]);
printf(" %f", V[i]);
}
}
推荐阅读
- r - 使用 r 中的 fread 从文件读取时解释换行符 \n 字符
- reactjs - 组件重新渲染生成问题
- c++ - 将 C++ 代码转换为 R 代码以生成数据
- gitlab - 如何增加 gitlab.com CI 中的内存限制?
- python-3.x - python中的返回语句在崇高的文本编辑器中不起作用
- mysql - 如何从我的 sql 数据库中获取最后一行元素?
- javascript - 文件系统不想在 Node.js 中写入特定文件
- c - 在 C 中显示二维数组中的随机字符串
- php - 你能解释一下这个 if 语句中双波浪号的目的吗?
- c++ - 在 Windows 中更新 clion 中的 cmake