首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >C# scanf int into struct

C# scanf int into struct
EN

Stack Overflow用户
提问于 2014-07-21 22:54:26
回答 1查看 43.9K关注 0票数 2

我正在尝试将一些整数读入一个结构中。我让用户输入两个3维向量,并返回两个叉积和点积。

它似乎跳过了第二个向量的第二个值。到目前为止,我的代码如下:

代码语言:javascript
复制
/** Write a program to calculate cross-products and dot products of 
**  a 3-dimensional vector:
**  
 **    1. Uses a type definition
**    2. Accepts User input of qty(2) 3-dimensional vectors
**    3. Calculate the cross-product of A x B and B x A                         
**    4. Calculate the dot product A * B
**
******************************************************************/


/************* Preprocessor Functions       **********************/
#include <stdio.h>
#include <stdlib.h>


/************ Structured Data Types ***************************/

typedef struct vector
{
    int x;
    int y;
    int z;
} Vector;


/*************   Declare User Functions  **********************/

int dot_product(Vector a, Vector b);
Vector cross_product(Vector a, Vector b);

/************     Begin MAIN LOOP     *************************/

int main(void)
{
/**      Declare variables     **/
    Vector a, b, c;

    printf("Enter the 3 integer components of the first vector: ");
    scanf("%d%d%d", &(a.x), &(a.y), &(a.z));
    printf("Enter the 3 integer components of the second vector: ");
    scanf("%d%d%d", &(b.x), &(b.y), &(b.y));
    c = cross_product(a, b);
    printf("\n\t(%d %d %d) x (%d %d %d) = (%d %d %d)",   a.x,a.y,a.z,b.x,b.y,b.z,c.x,c.y,c.z);
    c = cross_product(b, a);
    printf("\n\t(%d %d %d) x (%d %d %d) = (%d %d %d)", b.x,b.y,b.z,a.x,a.y,a.z,c.x,c.y,c.z);
    printf("\n\t(%d %d %d) * (%d %d %d) = %d\n", a.x,a.y,a.z,b.x, b.y,b.z,dot_product(a, b));

 /***********   AND CUT!  It's a wrap folks!  Take 5!     ***********/    
    return 0;
}

/**********    User Functions to perform the calculations    ****/

int dot_product(Vector a, Vector b)
{
    return((a.x*b.x)+(a.y*b.y)+(a.z*b.z));
}

Vector cross_product(Vector a, Vector b)
{
Vector c;
c.x = (a.y*b.z)-(a.z*b.y);
c.y = (a.z*b.x)-(a.x*b.z);
c.z = (a.x*b.y)-(a.y*b.x);

return(c);

}

如果用户输入:3 2 1,然后输入:5 6 2

使用的两个向量是:3 2 1和5 2 0

我在scanf中尝试了%d周围的空格,&a.x等周围没有括号。

感谢您的关注,任何帮助我们都将不胜感激。为了完全公开,这是针对我参加的一个C编程课程的。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2014-07-21 22:57:16

您读取了b.y两次:

scanf("%d%d%d", &(b.x), &(b.y), &(b.y));

最后一个应该是b.z,否则b.y被设置为6,然后被覆盖到2,而b.z永远不会被设置(并且恰好是0)。

票数 9
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/24868225

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档