将向量传递给函数以计算长度(C)
但如果输入了3dadswerudsad之类的内容,它仍然有效 此外,当用户为向量输入3个值时,如果为向量输入了除3个双精度以外的任何值,程序应以消息终止,因此我尝试了将向量传递给函数以计算长度(C),c,data-structures,structure,C,Data Structures,Structure,但如果输入了3dadswerudsad之类的内容,它仍然有效 此外,当用户为向量输入3个值时,如果为向量输入了除3个双精度以外的任何值,程序应以消息终止,因此我尝试了 #include <stdio.h> #include <stdlib.h> #include <math.h> struct vector { double x; double y; double z; }; stru
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
struct vector
{
double x;
double y;
double z;
};
struct vector *array;
double length(struct vector*);
int main()
{
int num,i;
double xin;
double yin;
double zin;
char buffer[30];
char buffer2[30];
printf("Enter number of vectors:");
fgets(buffer, 30, stdin);
sscanf(buffer, "%d", &num);
array = malloc( sizeof(struct vector) * num);
for(i=0;i<=num;i++)
{
printf("Please enter x y z for the vector:");
fgets(buffer2,100,stdin);
sscanf(buffer2, " %lf %lf %lf", &xin, &yin, &zin);
array[i].x = xin;
array[i].y = yin;
array[i].z = zin;
}
for(i=0;i<=num;i++)
{
printf( "Vector:%lf %lf %lf has a length of %lf\n", array[i].x, array[i].y, array[i].z, length(&array[i]));
}
}
double length(struct vector* vec)
{
return sqrt( (vec->x * vec->x) + (vec->y * vec->y) + (vec->z * vec->z) );
}
while( sscanf(buffer, "%d", &num) ==1 && num > 0 )
但它不会检查这些不正确的输入
我快发疯了你几乎是对的,你需要命名形式和函数,并适当地使用它:
while( sscanf(buffer2, "%lf %lf %lf", &xin, &yin, &zin) ==3 )
效率和其他原因,您可以考虑将指针传递给常数向量,因为不修改它。 然后您可以稍后使用
veclength(数组[i])
或veclengthptr(数组+i)
(与veclengthptr(&a[i])相同)
)
在使用这些函数之前,您应该给出原型(可能在某些头文件中):
double veclengthptr (const struct vector* v) {
return sqrt( (v->x * v->x) + (v->y * v->y) + (v->z * v->z) );
}
请注意,出于效率原因,您可能希望将这些原型声明为静态内联
(并在同一翻译单元中给出它们的实现),因此要求:
养成使用所有警告和调试信息进行编译的习惯,例如,gcc-Wall-Wextra-g
关于使用as
sscanf(buf、%d、&num)
请注意,如果buf
包含3dxde
,则通过将3
读入num
(使用dxde
未解析)成功。您可能希望在sscanf
中使用%n
(阅读其文档!),或者使用该函数可以按如下方式实现
static inline double veclength (struct vector);
将指针版本声明为double-vectlengthrptr(const-struct-vector*v)可能是有意义的,因为它没有对其目标进行任何修改。我的C-skills可能已经有点生疏了,但你不能将vectlength声明为double-vectlength(const-struct-vector&v)并忘记需要指针的函数吗?或者是C++中唯一的一个工作吗?没有公式<代码>(const结构向量和v)在C++中有效,但C中没有引用。如果我做VcLigTHRTPR,我的原型必须改变吗?哈哈,它一直在顶端,但是我得到了它的工作……谢谢大大帮助我投票失败,因为这个答案与如何检查无效输入无关,请看我对你先前问题的回答。(我认为这个问题应该是对前一个问题的编辑。)
double veclength (struct vector);
double veclengthptr (const struct vector*);
static inline double veclength (struct vector);
double length(struct vector vec)
{
return sqrt( vec.x*vec.x + vec.y*vec.y + vec.z*vec.z );
}