C calculation Error

取消
显示结果 
显示  仅  | 搜索替代 
您的意思是: 

C calculation Error

3,121 次查看
v_dave
Contributor IV
Using:
Codewarrior 8.1.1a build 7168 for the DSC56800/E
Target = 56F8323
USB Tap as debugger
 
I am having an interesting issue:


Code:
#define ONE_REV     200         //1.8deg per Full Step = 200 Steps for 1 Rev#define HALF_STEP_MULTIPLY            2    //Each Step = 1/2 Step#define NINE_EIGHTFIVE      985     //9.85typedef struct MOT_PARAM{ unsigned char  Mode;   // CW, CCW, Shortest unsigned char  Step_Mode;  //Full, Half, etc.. unsigned char Port_Position; //Current Position 0=Home unsigned char Port_Total;  //Total Ports on the Valve unsigned int    GearRatio;      //This is the Gear Ratio of the Motor unsigned int    Port_Deg;       // this is how many degree's between ports unsigned int QOffset;  //Quadrature Decoder Offset long            TotalSteps;     //Estimated number of steps for 1 revolution}mot_param;extern mot_param UA_Param;UA_Param.GearRatio = NINE_EIGHTFIVE;UA_Param.TotalSteps = (((UA_Param.GearRatio * ONE_REV) * HALF_STEP_MULTIPLY) / 100);

 

When this calculation is complete UA_Param.TotalSteps = 7

Should be 3940

I must be doing something wrong but not sure what yet. Any ideas?
标签 (1)
标记 (1)
0 项奖励
回复
3 回复数

1,014 次查看
Problem99
Contributor I
A separate "cast" operator is required, I think

UA_Param.TotalSteps = (( (long) UA_Param.GearRatio * ONE_REV * HALF_STEP_MULTIPLY) / 100 );


0 项奖励
回复

1,014 次查看
CompilerGuru
NXP Employee
NXP Employee
Without that cast, the compiler will use the int type to do all computations. With it, everything is done with longs. Basically ANSI always uses the types of the arguments of the operators, and as there were only ints involved, all computations are based on them. Well, the real rule is a bit more complex also caring about the signed vs unsigned types and more.

Daniel
0 项奖励
回复

1,014 次查看
v_dave
Contributor IV
Hello,
 
I just wanted to follow-up with the solution in case someone else has this problem.
 
The final result was to cast every variable:
 UA_Param.TotalSteps = (((long)UA_Param.GearRatio * (long)ONE_REV * (long)HALF_STEP_MULTIPLY) / 100);
 
0 项奖励
回复