【发布时间】:2015-03-07 18:20:58
【问题描述】:
#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) );
}
好的,上面的代码差不多完成了,它询问用户向量的数量,然后它询问用户这些向量的值,然后它会计算长度并相应地打印出来。
我试图在这里检查一些错误,但我似乎无法得到它...我查找了 fgets 和 sscanf 的所有可能返回值,我似乎无法得到它
防御功能
FIRST printf--------input 应该只是一个大于 0 的数字,EOF 应该返回类似 printf("enter a number--bye!") 这样的消息,所以我尝试了
while( sscanf(buffer, "%d", &num) ==1 && num > 0 )
但如果输入 3dadswerudsad 之类的内容,它仍然有效
此外,当用户输入向量的 3 个值时,如果为向量输入了除 3 个双精度之外的任何值,则程序应该以一条消息终止,所以我尝试了
while( sscanf(buffer2, "%lf %lf %lf", &xin, &yin, &zin) ==3 )
但它不会检查这些不正确的输入!!
我要疯了
【问题讨论】:
-
查看我对您之前问题的回答(我认为这个问题应该是对之前问题的修改。)
标签: c data-structures structure