【问题标题】:Array is showing different output in C数组在 C 中显示不同的输出
【发布时间】:2021-02-20 08:53:09
【问题描述】:

这是我卡住的 C 语言代码。

#include<stdio.h>

int main(){
    int Force_V[2], w;
    int i, j, Disp_V[2];
    printf("Enter Force Vector: ");
    for(i=0; i<=2; i++){
        scanf("%d", &Force_V[i]);
    }
    printf("Enter Displacement Vector: ");
    for(j=0; j<=2; j++){
        scanf("%d", &Disp_V[j]);
    }
    printf("Force vector: %di+%dj+%dk", Force_V[0],Force_V[1],Force_V[2]);
    printf("\nDisplacement vector== %di+%dj+%dk", Disp_V[0],Disp_V[1],Disp_V[2]);

    w= (Force_V[0]*Disp_V[0])+(Force_V[1]*Disp_V[1])+(Force_V[2]*Disp_V[2]);

    printf("The work: %df", w);

    return 0;

}

Force_V[2] 的输出显示 Disp_V[0] 的输出。谁能告诉我哪里出错了?

【问题讨论】:

  • 您需要声明大小为 3 的数组 Force_V 和 Disp_V。
  • 由于您似乎使用的是 3D 向量,因此数组的大小必须为 3,而不是 2。您的循环应该是 for (int i = 0; i &lt; 3; i++) — 这是在三个数组上循环的惯用形式元素。

标签: arrays c input output


【解决方案1】:

数组int Force_V[2] 有两个单元格,因此您必须像这样更改循环条件:

for(i=0; i<2; i++)

【讨论】:

    【解决方案2】:

    请注意,C 没有严格的数组索引检查。 您声明了数组int Force_V[2],这表示它有两个整数内存位置,索引为 0 和 1。然后,您尝试使用索引 2 设置和访问内存,该索引可能被其他变量使用。在您的情况下,它由 Disp_V 引用,但通常这会给出未定义的行为。

    #include<stdio.h>
    
    
    int main(){
        int Force_V[3], w;
        int i, j, Disp_V[3];
        printf("Enter Force Vector: ");
        for(i=0; i<3; i++){
            scanf("%d", &Force_V[i]);
        }
        printf("Enter Displacement Vector: ");
        for(j=0; j<3; j++){
            scanf("%d", &Disp_V[j]);
        }
        printf("Force vector: %di+%dj+%dk", Force_V[0],Force_V[1],Force_V[2]);
        printf("\nDisplacement vector== %di+%dj+%dk", Disp_V[0],Disp_V[1],Disp_V[2]);
    
        w= (Force_V[0]*Disp_V[0])+(Force_V[1]*Disp_V[1])+(Force_V[2]*Disp_V[2]);
    
        printf("The work: %df", w);
    
        return 0;
    
    }
    

    【讨论】:

    • 最好在 C(更惯用的 C)中使用 for (int i = 0; i &lt; 3; i++) 循环遍历具有 3 个元素的数组的元素。
    猜你喜欢
    • 1970-01-01
    • 2023-02-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-14
    • 2016-01-11
    • 2018-06-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多