bool Kitchen::checkStock(std::string &pizza) { std::string tmp; if (!checkNumber()) return (false); this->_need[doe] = 0; this->_need[tomato] = 0; this->_need[gruyere] = 0; this->_need[ham] = 0; this->_need[mushrooms] = 0; this->_need[eggplant] = 0; this->_need[goatcheese] = 0; this->_need[chieflove] = 0; this->_need[steak] = 0; checkStockOne(pizza); for (std::list<IPizzaTask *>::const_iterator it = this->_awaiting.begin(); it != this->_awaiting.end(); ++it) { tmp = (*it)->getType(); checkStockOne(tmp); } this->_stockMutex->lock(); for (std::map<IIngredient *, int>::const_iterator it2 = this->_stock.begin(); it2 != this->_stock.end() ; ++it2) { if (this->_need[(*it2).first->getType()] > (*it2).second) { this->_stockMutex->unlock(); return (false); } } this->_stockMutex->unlock(); return (true); }
void XlsSheet::parseXlsSheet( const xlsWorkSheet &xlsSheet ){ m_MaxRows = xlsSheet.rows.lastrow + 1; m_MaxColumns = xlsSheet.rows.lastcol; XlsRowStruct tmpRow; tmpRow.reserve( m_MaxColumns ); struct st_row::st_row_data *p_Row; for( int indexOfRow = 0; indexOfRow < m_MaxRows; ++indexOfRow ){ tmpRow.clear(); p_Row = &( xlsSheet.rows.row[indexOfRow] ); for( int indexOfColumn = 0; indexOfColumn < m_MaxColumns; ++indexOfColumn ){ if( p_Row->cells.cell[indexOfColumn].str != NULL ){ string xlsValue = reinterpret_cast<char*>( p_Row->cells.cell[indexOfColumn].str ); // 三方库转换数字问题:例如,1被转换为1.000000。需要去除后面额外添加的零。 if( checkNumber( xlsValue ) ){ xlsValue = xlsValue.substr( 0, xlsValue.find(".") ); } tmpRow.push_back( xlsValue ); } else{ tmpRow.push_back(""); } } m_XlsContent.push_back( tmpRow ); } DEBUG_D("end sheet parse"); }
bool operator() () { Number::setDefaultRoundingMode (FP_CONSTRUCTOR_TEST_ROUNDING_MODE); // // Note, since we're doing constructor tests, must use the full version // of checkNumber here, not the shortened version that takes a // reference number object. The other Number tests can use that // version, however here we must ensure the constructors themselves // are constructing the number properly, then it's valid for those // other tests to use the shortened version. // std::string name = std::string ("Floating Point Constructor ") + typeid (T).name (); return checkNumber ( name, Number::floatingPoint (floatVal_, dp_), expectedStrVal_, expectedIntVal_, expectedFracVal_, expectedDp_, expectedNegative_, expectedVal64Set_ ) ; }
int main(int argc, const char *argv[]) { struct Prime *head; head = malloc(sizeof(struct Prime)); (*head).primeNumber = 2; (*head).multipleOfPrime = 2; (*head).next = NULL; int i; for (i = 3;; i++) if (checkNumber(head, i)) printf("Added: %d\n", i); return 0; }
int main(int argc, const char * argv[]) { // insert code here... int a, b, c; printf("Give me three numbers between 100-999.\n"); while(1){ printf("A: \n"); scanf("%d", &a); if(checkNumber(a)==0){ break; } } while(1){ printf("B: \n"); scanf("%d", &b); if(checkNumber(b)==0){ break; } } while(1){ printf("C: \n"); scanf("%d", &c); if(checkNumber(c)==0){ break; } } int product=a*b*c; printf("A*B*C=%d\n", product); return 0; }
void Chipset::sendToRamString(const std::string &msg) { std::string word; std::vector<std::string> words; std::stringstream stream(msg); while (std::getline(stream, word, ' ')) { if (word.length() > 0) words.push_back(word.c_str()); } bool foundInstruction = false; size_t i; for (i = 0; i < _instVect.size(); i++) { if (words[0] == _instVect[i].name) { foundInstruction = true; break; } } if (foundInstruction == false) raiseException(BadInstException()); if (_instVect[i].nb_param != (words.size() - 1)) raiseException(SyntaxException()); Inst *new_Instruction; if (_instVect[i].nb_param >= 1) { eOperandType type = checkNumber(words[1]); size_t nb_end = words[1].find(")"); size_t nb_begin = words[1].find("("); std::string numberOnly = words[1].substr(nb_begin + 1, (nb_end - nb_begin) - 1); new_Instruction = new Inst(_instVect[i].inst, numberOnly, type); } else { new_Instruction = new Inst(_instVect[i].inst); } if (new_Instruction->getOpCode() == EXIT) _isExited = true; _ram.PutInst(new_Instruction); }
//density function double EMG::pdf(double z, int s ){ if (w==0){ return 0; } if (s==1){ z-=foot_print; }else{ z+=foot_print; } double vl = (l/2)*(s*2*(mu-z) + l*pow(si,2)); double p; if (vl > 100){ //potential for overflow, inaccuracies p = l*IN((z-mu)/si)*R(l*si - s*((z-mu)/si)); }else{ p = (l/2)*exp(vl)*erfc((s*(mu-z) + l*pow(si ,2) )/(sqrt(2)*si)); } vl = p*w*pow(pi, max(0, s) )*pow(1.-pi, max(0, -s) ); if (checkNumber(vl)){ return vl; } return 0.; }
int read_mat_input_parameters(char *pch, int size) { int i = 0; int j = 0; long value; int count = 0; readMatrixPtr = GetMatrixByName(pch, size, 1); if (readMatrixPtr == NULL) return MATRIX_NAME_NOT_FOUND; init_matrix(readMatrixPtr, size, 0); pch = strtok(NULL, " "); while (pch != NULL) { if (count == (size * size)) break; //printf("%s ", pch); if (checkNumber(pch, &value) == 0) { return INVALID_INPUT_NUMBER; } count++; // here we need to fill the matrix with those tokens if (i == size) { j++; i = 0; readMatrixPtr[i][j] = (int)value; } else { readMatrixPtr[i][j] = (int)value; } i++; pch = strtok(NULL, " "); } return OK; }
//cmd버퍼로부터 숫자를 잘라서 strBuf에 저장. //현재 int만 가능, 실수형도 가능하게끔 변경해야함. void XPath::NumberCpyFromCmdBuf() { int _startIdx = cmdIdx; while(checkNumber(cmdBuf[cmdIdx])) cmdIdx++; StrCpyNumber(strBuf, &cmdBuf[_startIdx], cmdIdx-_startIdx); }
/** * Divide two numbers * * @param other The left-hand-side of the division operation. * @param DivOP The type of division operation (divide, integer divide, or remainder) * * @return The division result. */ NumberString *NumberString::Division(NumberString *other, ArithmeticOperator divOP) { // buffers for intermediate results (just the numeric data) NumberStringBase accumBuffer; NumberStringBase saveLeftBuffer; NumberStringBase saveRightBuffer; // static sized buffers for typical calculation sizes. char leftBufFast[FAST_BUFFER]; char rightBufFast[FAST_BUFFER]; char outBufFast[FAST_BUFFER]; // NOTE: this is very similiar to the PowerDivide // method, these we kept as seperate routines since there // are enough subtile differences between the objectPointer operations // that combining them would make an already complex // algorithm even more so. When fixing/updating/adding to // this code also check PowerDivide for similiar updates // handle the zero cases, which are pretty quick. // if the other is zero, this is an error if (other->isZero()) { reportException(Error_Overflow_zero); } // if this number is zero, the result is also zero. if (isZero()) { return (NumberString *)IntegerZero; } // set of pointers for our temporary values NumberStringBase *accum = &accumBuffer; NumberStringBase *saveLeft = &saveLeftBuffer; NumberStringBase *saveRight = &saveRightBuffer; wholenumber_t digits = number_digits(); // either of these values might require rounding before starting the // operation, which might copy the values NumberString *left = checkNumber(digits); NumberString *right = other->checkNumber(digits); // calculate the probable result exponent from the two operand // exponends and the length difference. wholenumber_t calcExp = left->numberExponent - right->numberExponent; calcExp += left->digitsCount - right->digitsCount; // a negative exponent means this value will be less than // zero. If we are doing integer divide or remainder, we // // is exp < 0 and doing // or % if (calcExp < 0 && divOP != OT_DIVIDE) { // if this is integer division, the result is zero if (divOP == OT_INT_DIVIDE) { return (NumberString *)IntegerZero; } // for the remainder operation, this is the result (with suitable rounding, // of course) else { // this must be a new number value set with the current numeric values NumberString *result = left->prepareOperatorNumber(digits + 1, digits, NOROUND); result->setupNumber(); return result; } } size_t totalDigits = ((digits + 1) * 2) + 1; char *leftNum = leftBufFast; char *rightNum = rightBufFast; char *output = outBufFast; // we have automatic buffers for these that will handle typical // sizes. If larger than that, we allocate real buffer objects // and just allow them to be garbage collected at the end if (totalDigits > FAST_BUFFER) { // we can use a single buffer and chop it up leftNum = new_buffer(totalDigits * 3)->getData(); rightNum = leftNum + totalDigits; output = rightNum + totalDigits; } // make a copy of the input data into the buffers and pad the // rest of the buffer with zeros memcpy(leftNum, left->numberDigits, left->digitsCount); memset(leftNum + left->digitsCount, '\0', totalDigits - left->digitsCount); memcpy(rightNum, right->numberDigits, right->digitsCount); memset(rightNum + right->digitsCount, '\0', totalDigits - right->digitsCount); char *resultPtr = output; // copy the numberstring information as well *saveRight = *right; *saveLeft = *left; char *saveLeftPtr = NULL; char *saveRightPtr = NULL; // if this is a remainder, we need to save the pointers to // the original data if (divOP == OT_REMAINDER) { saveLeftPtr = leftNum; saveRightPtr = rightNum; // force the dividend sign to be positive. saveRight->numberSign = 1; } // the result sign is easy to compute (note, we use the saved // right sign, which might have been made positive for the // remainder operation accum->numberSign = left->numberSign * saveRight->numberSign; wholenumber_t rightPadding = 0; // we might need to pad the right number if it is shorter. // if the right is longer, we pad the left number to the same length if (saveRight->digitsCount > saveLeft->digitsCount) { // we're making the left number longer, which pads the number // because the rest of the number buffer is zeros. saveLeft->digitsCount = saveRight->digitsCount; } // the right number is shorter...we'll need to pad that out by the difference else { rightPadding = saveLeft->digitsCount - saveRight->digitsCount; // we want both numbers the same saveRight->digitsCount = saveLeft->digitsCount; } // set the new exponents using relative forms saveLeft->numberExponent = digits * 2 - saveLeft->digitsCount + 1; saveRight->numberExponent = rightPadding; wholenumber_t adjustLeft = 0; // When generating a best guess digits for result we will look // use the 1st 2 digits of the dividend (if there are 2) // we then add 1 to this DivChar to ensure than when we gues // we either guess correctly of under guess. // _______________ // aabbbbbb ) xxyyyyyyyy // // DivChar = aa + 1 // the division character is the first two digits, or // if there is only one digit, the second digit is effectively // a zero. int divChar = *rightNum * 10; if (saveRight->digitsCount > 1) { divChar += *(rightNum + 1); } // and add 1 to our division characters so that we will err on the // low side divChar++; // the count of digits in the result wholenumber_t resultDigits = 0; int thisDigit = 0; // We are now to enter 2 do forever loops, inside the loops // we test for ending conditions. and will exit the loops // when needed. This inner loop may need to break out of // both loops, if our divisor is reduced to zero(all finish // if this happens to do the no-no nad use a GOTO. // The outer loop is used to obtain all digits for the resul // We continue in this loop while the divisor has NOT been // reduced to zero and we have not reach the maximum number // of digits to be in the result (NumDigits + 1), we add // one to NumDigits so we can round if necessary. // The inner loop conputs each digits of the result and // breaks to the outer loop when the next digit of result // is found. // We compute a digit of result by continually taking best // guesses at how many times the dividend can go into the // divisor. Once The divisor becomes less than the dividend // we found this digit and we exit the inner loop. If the // divisor = dividend then we know dividend will go into // 1 more than last guess, so bump up the last guess and // exit both loops (ALL DONE !!), if neither of the above // conditions are met our last guess was low, compute a new // guess using result of last one, and go though inner loop // again. // outer loop for (; ; ) { int multiplier; // inner loop for (; ; ) { // are the two numbers now of equal length? if (saveLeft->digitsCount == saveRight->digitsCount) { // directly compare the two numbers int rc = memcmp(leftNum, rightNum, saveLeft->digitsCount); // if the left number is smaller, we're done with the inner // loop. if (rc < 0) { break; } // if the inner numbers are equal and this is not a remainder // op, we can terminate the entire loop else if (rc == 0 && divOP != OT_REMAINDER) { // divided evenly, if you add in one more to the guess *resultPtr++ = (char)(thisDigit + 1); resultDigits++; // this breaks out of both loops goto PowerDivideDone; } // either the number is greater or we're doing a remainder else { // just use one digit from the divisor for this next guess multiplier = *leftNum; } } // the left number is longer than the accumulator? else if (saveLeft->digitsCount > saveRight->digitsCount) { // calculate multiplier using the next two digits // note, since the left number is longer than the right, // we know we have at least two digis. multiplier = *leftNum * 10 + *(leftNum + 1); } // the divisor is smaller than the dividend, so we break out of the loop else { break; } // we found this digit of result, go to outer loop and finish up // processing for this digit. Compute Multiplier for actual divide multiplier = multiplier * 10 / divChar; // that is how many times will digit // of dividend go into divisor, using // the 1st 2 digits of each number // compute our Best Guess for this // digit // if this computed to zero, make it 1 if (multiplier == 0) { multiplier = 1; } // we know the divident goes into divisor at least one more time. thisDigit += multiplier; // divide the digit through and see if we guessed correctly. leftNum = subtractDivisor(leftNum, saveLeft->digitsCount, rightNum, saveRight->digitsCount, leftNum + saveLeft->digitsCount - 1, multiplier); // skip over any leading zeros leftNum = saveLeft->stripLeadingZeros(leftNum); // end of inner loop, go back and guess again !! This might have been the right guess. } // we only add zero digits if we have other digits. non-zero // digits always get added if (resultDigits != 0 || thisDigit != 0) { // add this to the result *resultPtr++ = (char) thisDigit; thisDigit = 0; resultDigits++; // we stop processing of A) the left number has been reduced // to zero or B) The result has reached our digits limit. if (*leftNum == '\0' || resultDigits > digits) { break; } } // we have different termination rules for int divide and remainder operations. if (divOP != OT_DIVIDE) { // have we generated all of the integer digits yet? // then we are done. if (calcExp <= 0) { break; } } // Was number reduced to zero? We divided evenly if (saveLeft->digitsCount == 1 && *leftNum == '\0') { break; } // we're not done dividing yet, we // need to adjust expected exponent // by one to the left calcExp--; // if we are still padding the right number, use one less digit on the // next pass if (rightPadding > 0) { saveRight->digitsCount--; rightPadding--; } // we decreased the left value to to the size of the right // before starting, so we add the digits back in as we progress. else { saveLeft->digitsCount++; } } // We've ended the entire division because we've hit equality. PowerDivideDone: ; // if this is a // or % operation, the result might be bad. // This might not be expressible as a whole number because of // the relative size of the operands, or we have a result with // no integer portion if ((divOP != OT_DIVIDE) && ((calcExp >= 0 && ( resultDigits + calcExp) > digits) || (calcExp < 0 && Numerics::abs(calcExp) > resultDigits))) { reportException(divOP == OT_REMAINDER ? Error_Invalid_whole_number_rem : Error_Invalid_whole_number_intdiv); } // if we're doing a remainder operation, we've really done an integer divide to this // point and now need to figure out the remainder portion if (divOP == OT_REMAINDER) { // if we managed to generate any result digits if (resultDigits != 0) { // the left number is the remainder. If the first digit // is zero, there is no remainder if (*leftNum != 0) { // this is our result resultPtr = leftNum; // now we need to calculate the exponent, adjusting for any added zeros saveLeftPtr += left->digitsCount; saveRightPtr = resultPtr + saveLeft->digitsCount + adjustLeft; accum->numberExponent = left->numberExponent - (saveRightPtr - saveLeftPtr); // the result length is the remaining digits count accum->digitsCount = saveLeft->digitsCount; } // we have a zero result, just return a zero else { return (NumberString *)IntegerZero; } } // no digits in result, remainder is the left number (this) else { // we return a copy of the left number NumberString *result = clone(); result->setupNumber(); return result; } } // this is a real division (but possibly integer division) so we need to finish up the result else { // if we have some sort of result digits, set up for building the final number string if (resultDigits != 0) { resultPtr = output; accum->digitsCount = resultDigits; accum->numberExponent = calcExp; // if the result is too big, we need to round to the digits setting if (accum->digitsCount > digits) { // we shorten the length and increase the exponent by the delta accum->numberExponent += (accum->digitsCount - digits); accum->digitsCount = digits; // see if we need to round accum->mathRound(resultPtr); } // We now remove any trailing zeros in the result. leftNum = resultPtr + accum->digitsCount - 1; // NOTE: We know we have at least one non-zero digit, so this loop // will not remove the entire result while (*leftNum == 0 && accum->digitsCount > 0) { leftNum--; // changes in length must be reflected with an equal and // opposite change in exponent. accum->digitsCount--; accum->numberExponent++; } } // no digits in the result, the answer is zero. This generally // only happens with integer division. else { return(NumberString *)IntegerZero; } } // ok, accum is the number data, resultPtr is the result data NumberString *result = new (accum->digitsCount) NumberString (accum->digitsCount); result->digitsCount = accum->digitsCount; result->numberExponent = accum->numberExponent; result->numberSign = accum->numberSign; // note, we have already rounded, so this should work without rounding now. result->adjustPrecision(resultPtr, digits); return result; }
int scanFile(FILE *fp){ if(fp == NULL){ printf("File could not be found.\n"); return -1; } printf("Reading in tokens..."); while(fpeek(fp) != EOF){ int tokenStart = fgetc(fp); int error = 0; //If we read whitespace, continue; if(tokenStart == '\n' || tokenStart == '\r' || tokenStart == '\t' || tokenStart == '\v' || tokenStart == ' '){ continue; } error = checkSymbols(fp, tokenStart); if(error == 4){ printf("ERROR Invalid symbol '%c'\n", tokenStart); exit(4); } else if(error == 0){ continue; } error = checkReservedWords(fp, tokenStart); if(error == -1){ error = checkVariable(fp, tokenStart); if(error == 3){ printf("ERROR Name exceeds 11 characters\n"); exit(3); } else if(error == 0){ continue; } } else if(error == 0){ continue; } error = checkNumber(fp, tokenStart); if(error == 2){ printf("ERROR number exceeds 5 digits\n"); exit(2); } else if(error == 1){ printf("ERROR Variables can't start with a letter"); exit(1); } else if(error == 0){ continue; } } createToken("null", 1); printf("COMPLETE\n"); return 0; }
int readOptions(char *path) { FILE *opt; char buf[400]; /* Flawfinder: ignore */ char option[200]; /* Flawfinder: ignore */ char value[200]; /* Flawfinder: ignore */ int temp1=0; int temp2=0; int i, k, buf_len; /* Flawfinder: ignore */ opt = fopen(settings, "r"); /* Flawfinder: ignore */ if (!opt) { if ( (quiet == 0) && (strcmp(path, "") != 0) ) { fprintf(stderr, _("Could not locate settings file\n")); fprintf(stdout, _("Creating folder: %s\n"), path); #ifdef _WIN32 mkdir(path); #else mkdir(path, (S_IRWXU | S_IRWXG | S_IRWXO)); #endif fprintf(stdout, _("Creating file: %s\n"), personal); createPersonalText(); fprintf(stdout, _("Creating file: %s\n"), internat); createInternationalDaysText(); fprintf(stdout, _("Saving options: %s\n"), settings); writeOptions(); } return 1; } while (!feof(opt)) { fgets(buf, 400, opt); buf[399] = '\0'; if (!feof(opt) && (buf[0]!='#' && buf[0]!='\n')) { sscanf(buf, "%200s : %200s", option, value); /* value may have space, keep string between "" */ buf_len=strlen(buf); for(i=0; i < buf_len && buf[i]!='"'; i++); i++; for(k=0;i<buf_len&&buf[i]!='"';value[k++]=buf[i++]); value[k]='\0'; /* terminate the value string */ if (strcmp(option, "quiet") == 0) { if (strcmp(value, "TRUE") == 0) { quiet=1; } else if (strcmp(value, "FALSE") == 0) { quiet=0; } else { if (quiet == 0) { fprintf(stderr, _("Invalid value at quiet setting in options file: %s\n"), value); } } } else if (strcmp(option, "show_X_next_days") == 0) { X = checkNumber(value, strlen(value)); if (X>365) { while(X>365) X-=365; if (quiet == 0) { fprintf(stderr, _("Very big number at show_X_next_days setting in options file: %s\nChanging to %d\n"), value, X); } } if (X<=0) { if (quiet == 0) { fprintf(stderr, _("Invalid value at show_X_next_days setting in options file: %s\n"), value); } X = 5; } } else if (strcmp(option, "name_database_file") == 0) { strncpy(database, value, BUFFER); } else if (strcmp(option, "personal_database_file") == 0) { strncpy(personal, value, BUFFER); } else if (strcmp(option, "international_days_database_file") == 0) { strncpy(internat, value, BUFFER); } #ifndef NO_GUI else if (strcmp(option, "autoclose_after_X_seconds") == 0) { auto_close = checkNumber(value, strlen(value)); if (auto_close == 0) { auto_close_flag = 1; } } #endif else if (strcmp(option, "show_personal_database") == 0) { if (strcmp(value, "TRUE") == 0) { temp1=0; } else if (strcmp(value, "FALSE") == 0) { temp1=1; } else { if (quiet == 0) { fprintf(stderr, _("Invalid value at show_personal_database setting in options file: %s\n"), value); } } } else if (strcmp(option, "show_international_days_database") == 0) { if (strcmp(value, "TRUE") == 0) { temp2=0; } else if (strcmp(value, "FALSE") == 0) { temp2=1; } else { if (quiet == 0) { fprintf(stderr, _("Invalid value at show_international_days_database setting in options file: %s\n"), value); } } } else { if (quiet == 0) { fprintf(stderr, _("Unknown settings in your options file:\n%s\n"), buf); } } } } if (temp1==1 && temp2==1) { no_database = 'a'; } else if (temp1==0 && temp2==1) { no_database = 'i'; } else if (temp1==1 && temp2==0) { no_database = 'p'; } else no_database = 'n'; fclose(opt); return 0; }
/** * Multiply two NumberString objects * * @param other The other object. * * @return A new numberstring that is the product of the two number strings. */ NumberString *NumberString::Multiply(NumberString *other) { wholenumber_t digits = number_digits(); // prepare both numbers, copying and rounding if necessary. NumberString *left = checkNumber(digits); NumberString *right = other->checkNumber(digits); // if either string is zero, then the result is also zero if (left->isZero() || right->isZero()) { return new_numberstring("0", 1); } // we can optimize things by using the smaller number for // the individual digit multiplcation, which will need fewer passes. NumberString *largeNum = left; NumberString *smallNum = right; if (left->digitsCount < right->digitsCount) { largeNum = right; smallNum = left; } // get our buffer size size_t totalDigits = ((digits +1) * 2) + 1; // fast allocation buffer char resultBufFast[FAST_BUFFER]; char *outPtr = resultBufFast; // if the digits are really big, then we need to allocate a larger buffer. // just allocate a buffer object and allow it to get garbage collected after // we're done. if (totalDigits > FAST_BUFFER) { outPtr = new_buffer(totalDigits)->getData(); } // make sure this is cleared out memset(outPtr, '\0', totalDigits); // set up the initial accumulator char *accumPtr = outPtr; wholenumber_t accumLen = 0; // this is where we start laying out the data...starting from the // far end of the buffer. char *resultPtr = accumPtr + totalDigits - 1; // we iterate through the small number multiplying with each of the // digits in the smaller number const char *current = smallNum->numberDigits + smallNum->digitsCount; // now process all of the digits for (size_t i = smallNum->digitsCount ; i > 0 ; i-- ) { current--; // get the current multiplier character int multChar = *current; // we don't need to do anything with zero digits. Other digits // we multiply and add if (multChar != 0) { // multiply the larger number by the current digit and add to the accumulator accumPtr = addMultiplier(largeNum->numberDigits, largeNum->digitsCount, resultPtr, multChar); } // back up the result pointer for the next add position and handle the next digit. resultPtr--; } // update the accumulator length for the final result. accumLen = (++resultPtr - accumPtr) + smallNum->digitsCount; // accumPtr now points to result, // the len of result is in accumLen wholenumber_t extraDigits = 0; // if this is longer than the current digits, the excess is added into the // exponent if (accumLen > digits) { // we also need to chop the length to digits + 1 (we'll use that to round // the final result) extraDigits = accumLen -(digits + 1); accumLen = digits + 1; } // now get a numberstring object large enough to hold this result NumberString *result = new_numberstring(NULL, accumLen); // the result exponent is the sum of the two operand exponents + the adjustment amount result->numberExponent = largeNum->numberExponent + smallNum->numberExponent + extraDigits; // the sign is computed by multiplying the signs result->numberSign = largeNum->numberSign * smallNum->numberSign; result->digitsCount = accumLen; // make sure this is in the correct precision (also copies the digits into // the result object). result->adjustPrecision(accumPtr, digits); return result; }
solution solve(string &c, bigNumber previous, settings &user) { c += '$'; PTYPE pType=ERROR; vector<int> first; vector<int> second; bigNumber bn1; bigNumber bn2; bigNumber temp; bn1.setBase(user.getBase()); bn2.setBase(user.getBase()); temp.setBase(user.getBase()); int decimalCount1=0; int decimalCount2=0; int commaNumbers=0; int numbers=0; bool decimal=false; bool comma=false; bool negative1=false; bool negative2=false; bool done=false; bool printExact=false; bool printStats=false; bigNumber* targetBN = &bn1; vector<int>* targetVec = &first; int* targetDec = &decimalCount1; bool* targetNegative = &negative1; int counter = c.size(); for (int i=0; i<counter; i++) { if (checkWord(c, i, "pi")) { if (numbers>0 || comma==true || decimal==true) { RETURN_ERROR; } else { string piString(PI); for (int piMarker=PRECISION; piMarker>=0; piMarker--) { char piChar = '0'; int piNum = piString[PRECISION-piMarker] - piChar; (*targetVec).push_back(piNum); } done=true; *targetDec = PRECISION; numbers += (PRECISION+1); counter += 2; i += 2; } } if (checkWord(c, i, "theta")) { if (numbers>0 || comma==true || decimal==true) { RETURN_ERROR; } else { string thetaString(THETA); for (int thetaMarker=PRECISION; thetaMarker>=0; thetaMarker--) { char thetaChar = '0'; int thetaNum = thetaString[PRECISION-thetaMarker] - thetaChar; (*targetVec).push_back(thetaNum); } done=true; *targetDec = PRECISION; numbers += (PRECISION+1); counter += 5; i += 5; } } //if it isn't a space, number, symbol, end marker, or decimal point, return error if (checkSpace(c[i])==false && isNumber(c[i], user)==false && isSymbol(c[i])==false && c[i] != '$' && c[i] != ',' && c[i] != '.') { RETURN_ERROR; } if (c[i]==',') { if (comma==false) { if (decimal==true || numbers==0 || numbers > 3 || done==true) RETURN_ERROR; else comma = true; } else if (commaNumbers != 3) RETURN_ERROR; commaNumbers=0; } //if it's a space else if (checkSpace(c[i])==true) { //if it's preceeded by a number, number is complete if (isNumber(c[i-1], user)) { done = true; } //if negative is set, and it is preceeded by a minus symbol, return error else if (checkSymbol(c[i-1]) == SUBTRACT && *targetNegative == true) { RETURN_ERROR; } } //if it's a number else if (isNumber(c[i], user)) { //if number was complete, return error if (done==true) { RETURN_ERROR; } if (comma==true) commaNumbers++; //otherwise add number to target vector, add decimal count if needed (*targetVec).push_back(checkNumber(c[i])); numbers++; if (decimal==true) { (*targetDec)++; } } //if it's a minus symbol else if (checkSymbol(c[i]) == SUBTRACT) { //if no numbers have been added if (numbers==0) { //if target isn't negative, make target negative if ((*targetNegative)==false) { (*targetNegative) = true; (*targetBN).setNegative(); } //if target is negative, no numbers have been added, and the target is the first number: //there are two minus symbols, which means the intent is to //subtract a negative number from previous else if (targetBN == &bn1) { pType = SUBTRACT; targetBN = &bn2; numbers=0; commaNumbers=0; comma=false; bn2.setNegative(); //sets 2nd number to negative negative2=true; //sets 2nd number to negative targetNegative= &negative2; done=false; targetDec = &decimalCount2; targetVec = &second; decimal=false; } else { RETURN_ERROR; } } //if numbers have been added, and the target is the first number, the problem type is subtraction else if (targetBN == &bn1) { if (comma==true && decimal==false && commaNumbers != 3) RETURN_ERROR; pType = SUBTRACT; numbers=0; commaNumbers=0; comma=false; done=false; targetBN = &bn2; targetNegative= &negative2; targetDec = &decimalCount2; targetVec = &second; decimal=false; } //if numbers have been added, and the target is the second number, return error else { RETURN_ERROR; } } //if it's a symbol other than minus else if (checkSymbol(c[i]) != ERROR && checkSymbol(c[i]) != SUBTRACT) { //if the type is already established, return error if (pType != ERROR) { RETURN_ERROR; } //otherwise, set problem type based on symbol and reset figures else { if (comma==true && decimal==false && commaNumbers != 3) RETURN_ERROR; pType = checkSymbol(c[i]); targetBN = &bn2; numbers=0; commaNumbers=0; comma=false; done=false; targetNegative = &negative2; targetDec = &decimalCount2; targetVec = &second; decimal=false; } } //if it's a decimal point else if (c[i]=='.') { //if there's already been a decimal point, return error if (decimal==true) { RETURN_ERROR; } else decimal = true; if (comma==true && commaNumbers != 3) RETURN_ERROR; } //if it's an endline character else if (c[i] == '$') { if (comma==true && decimal==false && commaNumbers != 3) RETURN_ERROR; //if both numbers are empty if (first.size()==0 && second.size()==0) { if (pType==FACTORIAL) { bn1 = previous; } else RETURN_ERROR; } //if first number is empty, set bn1 to previous if (first.size()==0) { bn1 = previous; } //otherwise create bn1 from entered and print it as is else { bn1 = numberFromVector(first, negative1, decimalCount1, user); printExact=true; } //if second number is empty if (second.size()==0) { //if first number is negative and pType is undefined, subtract number from previous if (negative1==true && pType == ERROR) { bn1.setPositive(); temp = previous - bn1; cout << "Entered: "; displayNumber(previous, user, false, false); cout << " - "; displayNumber(bn1, user, true, false); RETURN_OK(temp); //return solution(temp, 0); } //if first number isn't negative and no problem type has been declared, return that number else if (pType == ERROR) { cout << "Entered: "; displayNumber(bn1, user, true, false); RETURN_OK(bn1); //return solution(bn1, 0); } else if (pType != FACTORIAL) { RETURN_ERROR; } } //otherwise take ints from second vector and use to set bigNumber2 else { bn2 = numberFromVector(second, negative2, decimalCount2, user); } cout << "Entered: "; displayNumber(bn1, user, printExact, printStats); break; } } //use problem type to calculate solution, return with no errors if valid switch(pType) { case ERROR: RETURN_ERROR; case ADD: cout << " + "; bn2.printNumber(); temp = bn1 + bn2; RETURN_OK(temp); case SUBTRACT: cout << " - "; bn2.printNumber(); temp = bn1 - bn2; RETURN_OK(temp); case MULTIPLY: cout << " * "; bn2.printNumber(); temp = bn1 * bn2; RETURN_OK(temp); case DIVIDE: cout << " / "; bn2.printNumber(); if (bn2==0) { RETURN_ERROR; } temp = bn1 / bn2; RETURN_OK(temp); case FACTORIAL: if (bn1<0 || bn1.getDecimalCount() > 0) { RETURN_ERROR; } else if (bn1==0) { cout << "!"; bigNumber fact(1); fact.setBase(user.getBase()); RETURN_OK(fact); } temp = bigNumber::factorial(bn1); cout << "!"; RETURN_OK(temp); case EXPONENT: cout << "^"; bn2.printNumber(); temp = bigNumber::exponent(bn1, bn2); RETURN_OK(temp); case ITERATION: cout << "c"; bn2.printNumber(); temp = bigNumber::iterations(bn1, bn2); RETURN_OK(temp); default: RETURN_ERROR; } }
//입력받은 커맨드를 분석하고 실행함. //자료의 형태는 트리이며, //탐색 방식은 크게 두가지가 존재함. //1.재귀호출을 이용한 트리 전체 순회 방식 //2.큐를 이용한 깊이별 탐색 방식 int XPath::XPathCmdParser(wchar_t* _cmdBuf, XMLNode* _XpathRoute) { cmdIdx = 0; wcscpy(cmdBuf, _cmdBuf); ClearQ(); //탐색한 노드 저장용 큐 초기화 //루트 부터 탐색하기 위해 루트의 부모 노드가 필요함. XMLNode* tempNode = new XMLNode; tempNode->setName(L"Root's Parent"); //이름 설정 tempNode->setChildNode(_XpathRoute);//루트를 자식으로 설정 searchNodeQ.push(tempNode);//큐에 push함. while(cmdBuf[cmdIdx] != L'\0') { RemoveBlank(cmdBuf, &cmdIdx); //cmd : / if(cmdBuf[cmdIdx] == L'/') { //cmd : // if(cmdBuf[cmdIdx+1] == L'/') { //cmd : //* if(cmdBuf[cmdIdx+2] == L'*') { cmdIdx = cmdIdx + 3; // cmd : //* 이후로 인덱스 이동 Search_All_NonString(searchNodeQ.front()); //문자열에 관계없이 루트노드부터 전부 저장. searchNodeQ.pop(); //방금 했던 탐색의 루트가 됐던 큐 제거 printType = print_Name; //출력 타입을 이름으로 설정. } //cmd : //@ else if(cmdBuf[cmdIdx+2] == L'@') { //cmd : //@attributeName if(checkAlpha(cmdBuf[cmdIdx+3])) { cmdIdx = cmdIdx + 3; //cmd버퍼의 인덱스를 첫번째 알파벳으로 위치시킴. StrCpyFromCmdBuf(); //cmd버퍼에서 단어단위로 잘라서 복사함. RemoveBlank(cmdBuf, &cmdIdx); //잘라낸 이후에 공백이 있을수도 있으니 cmd버퍼의 공백 제거 ClearQ(); //노드를 저장할 큐를 비움. //루트부터 잘라낸 str과 일치하는 속성이름을 검색하여 큐에 저장함. Search_All(_XpathRoute, strBuf, search_AttributeName); printType = print_Value;//출력값을 value로 설정. } else ErrorCollection(L"//@"); } //cmd : //tagName else if(checkAlpha(cmdBuf[cmdIdx+2])) { cmdIdx = cmdIdx + 2; //cmd : //이후로 인덱스 이동 StrCpyFromCmdBuf(); //cmd 버퍼에서 str 버퍼로 커맨드 이동 RemoveBlank(cmdBuf, &cmdIdx); //cmd버퍼 공백제거 ClearQ(); //큐 비우기 Search_All(_XpathRoute, strBuf, search_TagName); //루트 부터 탐색하여 strBuf에 있는 문자열과 일치하는 노드 저장. printType = print_Value;//출력값을 value로 설정. } else ErrorCollection(L"//"); } //cmd : /* else if(cmdBuf[cmdIdx+1] == L'*') { int tempQSize = searchNodeQ.size(); //임시 큐 사이즈 저장. size()함수 그대로 사용하면 값이 계속 바뀌기 때문. while(tempQSize--) { Search_All_NonString(searchNodeQ.front());//큐에 저장된 노드들 기준으로 문자열과 상관없이 탐색하여 모든 노드를 큐에 저장. searchNodeQ.pop(); //방금 했던 탐색의 루트가 됐던 큐 제거 } cmdIdx = cmdIdx + 2; //cmd : /* 이후로 인덱스 이동 printType = print_Name; } //cmd : /tagName else if(checkAlpha(cmdBuf[cmdIdx+1])) { cmdIdx = cmdIdx + 1; //cmd : /a a로 인덱스 이동 StrCpyFromCmdBuf(); //strBuf로 문자열 복사 Search_Child(strBuf);//strBuf에 저장된 문자열을 기준으로 큐에 있는 노드의 자식들을 탐색함. printType = print_Value;//출력타입을 값으로 지정. } else ErrorCollection(L"/"); } //cmd : [ else if(cmdBuf[cmdIdx] == L'[') { //cmd : [1 if(checkNumber(cmdBuf[cmdIdx+1])) { cmdIdx = cmdIdx + 1; //cmd : [1 1로인덱스 이동 NumberCpyFromCmdBuf(); //문자열중 연속된 숫자들만 strBuf로 복사 RemoveBlank(cmdBuf, &cmdIdx);//혹시 모를 공백 제거 //cmd : [1] if(cmdBuf[cmdIdx] == L']') //cmd : [1] { cmdIdx++; int selectCnt = _wtoi(strBuf); //strBuf에 있는 문자열 -> int형으로 변경. []안에 있는 숫자가 몇인지 저장. if((int)searchNodeQ.size() >= selectCnt) { while(--selectCnt) searchNodeQ.pop(); //[]안의 숫자만큼 큐안의 노드 제거 searchNodeQ.push(searchNodeQ.front());//원하는 노드를 제일 뒤로 넣음 while(searchNodeQ.size()-1) searchNodeQ.pop();//원하는 노드 빼고 전부 팝 printType = print_Value; } else ErrorCollection(L"[999]"); } else ErrorCollection(L"[999"); } //cmd : [a else if(checkAlpha(cmdBuf[cmdIdx+1])) { //cmd : [func( if(checkAnyChar(&cmdBuf[cmdIdx+1], L'(', L']')) { //cmd : func( 에서 (위치를 checkFunc에 기록. int checkFunc = checkAnyChar(&cmdBuf[cmdIdx+1], L'(', L']'); //cmd : [func()] if(cmdBuf[cmdIdx + 1 + checkFunc + 1] == L')') { cmdIdx = cmdIdx + 1; //cmd : [func( 에서 f위치로 이동. StrCpyFromCmdBuf(); //cmd : [func( 에서 f부터 알파벳,숫자,-_. 가 아닌곳 직전까지 복사. (앞까지 복사될것임. FuncCollection(strBuf);//위에서 복사한 문자열로 어떤 함수인지 처리. cmdBuf[cmdIdx] = L'\0'; } else ErrorCollection(L"[func("); } else ErrorCollection(L"[name~$"); } //cmd : [@ else if(cmdBuf[cmdIdx] == L'@') { cmdBuf[cmdIdx] = L'\0'; } else ErrorCollection(L"[~"); } //cmd가 /,[ 로 시작하지 않을때. else ErrorCollection(L"cmd"); } //searchNodeQ에 있는 노드들 출력 PrintNodeQ(); delete tempNode; return 0; }
int main() { record queue[10000]; long int ele, pr; char ch; scanf("%c",&ch); getchar(); do { switch(ch) { case 'a': scanf("%ld",&ele); scanf("%ld",&pr); getchar(); if(checkNumber(ele) && checkNumber(pr) && ele >= 0 && pr >=1) { insert(queue, ele, pr); size++; } else { printf("Enter elements in given range.\n"); } break; case 'e': extract_min(queue); break; case 'g': get_min(queue); break; case 'd': scanf("%ld",&ele); scanf("%ld",&pr); getchar(); if(checkNumber(ele) && checkNumber(pr) && ele >= 0 && pr >=1) { decrease_priority(queue, ele, pr); } else { printf("Enter elements in given range.\n"); } break; case 's': printf("\n"); break; default: printf("Enter correct choice.\n"); break; } scanf("%c",&ch); getchar(); } while(ch != 's'); return 0; }
bool isNumber(char const &c, settings &user) { return (checkNumber(c) >= 0 && checkNumber(c) <= (user.getBase()-1) ); }
void modifySettings(settings &user) { cout << endl; string setI; string setS; bool invalid=false; int intSet=0; do { intSet=0; invalid=false; setI.clear(); cout << "Enter desired precision: "; std::getline(cin, setI); for (int i=0; i<setI.size(); i++) { int target = setI.size()-i-1; if (checkNumber(setI[target]) < 0 || checkNumber(setI[target]) > 9) { cout << "Invalid entry" << endl << endl; invalid=true; break; } else intSet += (checkNumber(setI[target]) * pow(10, i)); } if (invalid==false) { if (intSet>PRECISION) { cout << "Invalid entry (precision must be between 0 and " << PRECISION << ")" << endl << endl; invalid=true; } else { user.setRound(intSet); } } } while (invalid==true); do { intSet=0; invalid=false; setI.clear(); cout << "Enter desired base: "; std::getline(cin, setI); for (int i=0; i<setI.size(); i++) { int target = setI.size()-i-1; if (checkNumber(setI[target]) < 0 || checkNumber(setI[target]) > 9 ) { cout << "Invalid entry" << endl << endl; invalid=true; break; } else intSet += (checkNumber(setI[target]) * pow(10, i)); } if (invalid==false) { if (intSet < 2 || intSet > 36) { cout << "Invalid entry (base must be between 2 and 36)" << endl << endl; invalid=true; } else { user.setBase(intSet); } } } while (invalid==true); for (;;) { if (user.getPercent()) { setS.clear(); cout << "Turn off percentages? "; std::getline(cin, setS); if (setS=="yes" || setS=="y") { user.percentOff(); break; } else if (setS=="no" || setS=="n") { break; } else { cout << "Invalid entry" << endl << endl; continue; } } else { setS.clear(); cout << "Turn on percentages? "; std::getline(cin, setS); if (setS=="yes" || setS=="y") { user.percentOn(); break; } else if (setS=="no" || setS=="n") { break; } else { cout << "Invalid entry" << endl << endl; continue; } } } for (;;) { setS.clear(); if (user.getShowDigits()) { cout << "Hide number stats? "; std::getline(cin, setS); if (setS=="yes" || setS=="y") { user.showDigitsOff(); break; } else if (setS=="no" || setS=="n") { break; } else { cout << "Invalid entry" << endl << endl; continue; } } else { cout << "Show number stats? "; std::getline(cin, setS); if (setS=="yes" || setS=="y") { user.showDigitsOn(); break; } else if (setS=="no" || setS=="n") { break; } else { cout << "Invalid entry" << endl << endl; continue; } } } cout << endl << endl; }