首页 > 解决方案 > 如何用新值覆盖用户输入的向量的分量?

问题描述

刚开始学习 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]));
    }
}

标签: cvectoroverriding

解决方案


在查看评论部分并遵循@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]);
    }
}


推荐阅读