[英]c++ if statements always return true
我有一堆有閾值的數學操作,但無論我改變什么,if 語句總是返回 true。 沒有編譯錯誤,無法讓調試器工作。 這是一個函數,XY 和 Z 數組都是正確的(我打印它們是為了更早檢查),數學至少對於刀片距離檢查是正確的,但總是返回 true。 我通過 matlab 運行了相同的代碼(顯然是重寫的),它根據我的數據返回 true 或 false,所以很明顯它與我寫這個的方式有問題。 還有什么辦法可以使這個變薄嗎?
bool Device::_SafeD(char _Type, float _Data[20][3]) {
bool S;
double x[20], y[20], z[20];
for (int i=0; i<20; i++) {
x[i] = _Data[i][0];
y[i] = _Data[i][1];
z[i] = _Data[i][2];
}
// Check angles for needle
if (_Type == 'n') {
for (int i=0; i<20; i++) {
float dot, moda, modb, c, angle;
dot = ((x[i]*x[i+1]) + (y[i]*y[i+1]) + (z[i]*z[i+1]));
moda = sqrt(pow(x[i],2)+pow(y[i],2)+pow(z[i],2));
modb = sqrt(pow(x[i+1],2)+(y[i+1],2)+(z[i+1],2));
c = dot/(moda*modb);
angle = acos(c);
if (angle > 45){
S = 0;
} else {
S = 1;
}
}
}
// Check distance for blade
if (_Type == 'b'){
for (int i=0; i<19; i++) {
float distance = (x[i+1]-x[i]) + (y[i+1]-y[i]) + (z[i+1]-z[i]);
cout << "distance " << distance << endl;
if (distance > 5.0) {
S = 0;
} else {
S = 1;
}
}
}
if (S == 0) {
return 0;
}
if(S == 1) {
return 1;
}
}
干杯
最可能的錯誤是您將angle
與角度進行比較,而acos
的返回值以弧度為單位。
if (angle > 45){
在與 45 比較之前將角度轉換為度數,您應該沒問題。
if (radians_to_degrees(angle) > 45){
在哪里
double radians_to_degrees(double in)
{
return (in*180/M_PI);
}
另一種選擇是以弧度計算 45 度的等效值並將其與angle
進行比較。
double const radian_45 = M_PI*45.0/180;
並使用
if (angle > radian_45){
@Bob__ 在評論中清楚地說明了另一個錯誤:
OP 使用兩個循環來檢查角度和距離,在這些循環中,一個標志 (
S
) 被設置為0
或1
,但它對數組中的每個索引都進行了檢查,因此它被覆蓋了。 整個函數的返回值(在提供的代碼中)僅取決於數組中的最后兩個元素。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.