在学习java之后我正在尝试学习c++。有人告诉我,这些结构很像 java 中具有实例变量的类。在 isDivisible 函数中,fraction 结构中的“整体”值似乎从 1 随机变为 0。为什么会这样?请不要吝啬细节。谢谢您的帮助
#include <stdio.h>
#include <math.h>
#include <iostream>
using namespace std;
#define LARGEST(a,b) ((a > b) ? 1 : 0)
struct fraction {
int numerator;
int denominator;
int whole;
};
fraction* wholeNumber(fraction * frac){
if (LARGEST((frac->numerator), (frac->denominator)) == 1){
double w = (((double) (frac->numerator)) / ((double) (frac->denominator)));
int whole = floor(w);
struct fraction now = { (frac->numerator) - whole*(frac->denominator),
(frac->denominator), whole};
return &now;
}
return frac;
}
int toCheck[4] = {2,3,5,7};
int isDivisible(fraction * frac){
double newNum = (double) frac->numerator;
double newDen = (double) frac->denominator;
// The value of whole seems to change right about here after the two doubles are declared
for(int i = 0; i < 4; ++i){
if (( (newNum / toCheck[i]) == (frac->numerator / toCheck[i]) ) ? true : false &&
((newDen / toCheck[i]) == (frac->numerator / toCheck[i]) ) ? true : false)
return toCheck[i];
}
return 0;
}
fraction* simplifier(fraction * frac){
frac = wholeNumber(frac);
while(isDivisible(frac) != 0){
int factor = isDivisible(frac);
frac->numerator = frac->numerator / factor;
frac->denominator = frac->denominator / factor;
}
return frac;
}
int main (int argc, char ** argv){
struct fraction frac = {55, 50, 0}; // fraction declared, 0 55/50
struct fraction * final = simplifier(&frac);
printf("%d %d/%d\n", final->whole, final->numerator, final->denominator);
return 0;
}