/** * Agrega todos os valores a partir de uma localizacao num ficheiro * @param prefixo e a localizacao a partir do qual vao ser agregados os valores * @param nivel e o nivel de detalhe da agregacao * @param path e o nome do ficheiro onde deve ser colocada essa agregacao */ int agregar(char* prefixo[], int nivel, char* path){ // TEM DE BLOQUEAR ENQUANTO ESCREVE unlink(path); DistritoFluRecord *distrito = getByNameDist(prefixo[0]); ConcelhoFluRecord *tmpC = NULL; FreguesiaFluRecord *tmpF = NULL; char *tamanho=(char*)malloc(10); if(distrito == NULL){ return E_AGRIMPOSSIVEL;} //retorna que a agregacao é impossivel int fdEscrita = open(path, O_CREAT| O_TRUNC | O_WRONLY, 0666); if(fdEscrita<0) return E_FICHEIRO;//mensagem_de_erro(E_FICHEIRO); switch (nivel) { case 0: write(fdEscrita, distrito->nome,strlen(distrito->nome)); write(fdEscrita, ":", 1); clearbuffer(tamanho, 10); sprintf(tamanho,"%d",(distrito->aggregate)); write(fdEscrita, tamanho, sizeof(tamanho)-1); write(fdEscrita, "\n", 1); break; case 1: for(tmpC = distrito->concelhos; tmpC!=NULL; tmpC=tmpC->next){ write(fdEscrita, distrito->nome,strlen(distrito->nome)); write(fdEscrita, ":", 1); write(fdEscrita, tmpC->nome,strlen(tmpC->nome)); write(fdEscrita, ":", 1); clearbuffer(tamanho, 10); sprintf(tamanho,"%d",(tmpC->aggregate)); write(fdEscrita, tamanho, numDigits(tmpC->aggregate)); write(fdEscrita, "\n", 1); } break; case 2: for(tmpC = distrito->concelhos; tmpC!=NULL; tmpC=tmpC->next) for(tmpF = tmpC->freguesias; tmpF!=NULL; tmpF=tmpF->next){ write(fdEscrita, distrito->nome,strlen(distrito->nome)); write(fdEscrita, ":", 1); write(fdEscrita, tmpC->nome,strlen(tmpC->nome)); write(fdEscrita, ":", 1); write(fdEscrita, tmpF->nome, strlen(tmpF->nome)); write(fdEscrita, ":", 1); clearbuffer(tamanho, 10); sprintf(tamanho,"%d",(tmpF->aggregate)); write(fdEscrita, tamanho, numDigits(tmpF->aggregate)); write(fdEscrita, "\n", 1); } default: break; } if(fdEscrita>=0) close(fdEscrita); return 0; }
/** \brief Practical function to write point as string. * * Format: "(x,y)" * Example: (2,1) */ NString asString() const { const U8 countDigits = numDigits(static_cast<S32>(xVal))+ numDigits(static_cast<S32>(yVal)); const U8 numChars = 3; NString ret(numChars+countDigits); ret.append('('); ret.append(xVal); ret.append(','); ret.append(yVal); ret.append(')'); return ret; }
String MenuRowVar::fullText() { String s = this->text + ": "; for (int i = 0; i < this->maxDigits() - numDigits(*this->var); i++) s += '0'; s += to_string(*this->var) + units; return s; }
bool FormatString::checkArgument(unsigned pos, unsigned& argNumber, unsigned& offset) { bool result = false; offset = 1; // the "%" sign argNumber = 0; for (unsigned i = 0; i < numDigits(maxArguments); ++i) { if ((pos + i + 1) < input.size()) { unsigned number = (int)input.at(pos + i + 1) - ASCIINumbersOffset; // offset for "%" sign if (number < decimalDigits) { argNumber = argNumber * decimalDigits + number; result = true; ++offset; } else { break; } } else { break; } } if (argNumber != 0) { --argNumber; } return result; }
uint64_t solve62() { uint64_t cubes[8500] = { 0 }; int permutationsCount = 0; for( uint64_t i = 345; i < 8500; ++i ) { cubes[i] = i * i * i; } for( int i = 345; i < 8500; ++i ) { permutationsCount = 1; for( int j = i + 1; j < 8500; ++j ) { if( cubes[j] > pow( 10, numDigits( cubes[i] ) ) ) { break; } if( arePermutations( cubes[i], cubes[j] ) ) { permutationsCount++; } } if( permutationsCount == 5 ) { return cubes[i]; } } return 0; }
static inline std::string processScore(int x) { std::stringstream padding; for(int i = numDigits(x); i < 7; i++) { padding << "0"; } std::stringstream type; type << x; return padding.str() + type.str(); }
int contiene (int n,char c){ char cadena[numDigits(n)]; sprintf(cadena,"%i",n); int i; for (i=0;i<strlen(cadena);i++){ if (cadena[i]==c) return 1; } return 0; }
/* returns the number of digits found in the given number */ int numDigits( int number ){ static int count; if (number < 10 ) { count++; return count; } else { count++; return ( numDigits( number/ 10 ) ); } }
uint8_t* setArrVal(uint64_t n, size_t size){ int64_t i, j=numDigits(n), k=j, temp; uint8_t* a = malloc(sizeof(uint8_t)*size); for(i=0; i<k; i++){ temp = (int64_t)(n % (int64_t)pow(10, j--)); temp /= (int64_t)(pow(10, j)); a[i] = (uint8_t)temp; } return a; }
int SevenSegment::displayNum(double value, int dp, boolean lzsuppress) { byte segments[NDIGITS]; long integerValue; long fractionValue; double iValue; double fValue; int digitIndex = 0; int intDigits = maxdigits; if (dp > maxdigits) return -1; if (value < 0.0) negative = 1; else negative = 0; if (negative) value = -value; fValue = modf(value,&iValue); fValue += .005; //This is added so that the truncation on line 59 will behave like //the rounding in the lcd and serial libraries. integerValue = (long) iValue; fractionValue = (long) (fValue * Pow10(dp)); if (negative) { --intDigits; ++digitIndex; } intDigits -= dp; // check here for overflow if (numDigits(value) > intDigits) { return -1; //FIX DINGER //Add some logic to remove the digits greater than we can display //And display only the digits that we can. } calcValue(integerValue,intDigits,digitIndex); if (dp != 0) { calcValue(fractionValue,dp,digitIndex+intDigits); } digitIndex = 0; intDigits = maxdigits; if (negative) { segments[0] = MinusSegments; ++digitIndex; } for (int i = digitIndex; i < maxdigits; ++i) { segments[i] = pgm_read_byte (& DigitSegments[digits[i]]); } if (lzsuppress) { for (int i = digitIndex; i < maxdigits; ++i) { if (digits[i] != 0) break; if (dp > 0 && i <= ((maxdigits-1)-dp)) { segments[i] = 0x00; } } } if (dp != 0) segments[(maxdigits-1)-dp] |= DecPoint; segOutput(segments); return 0; }
void ZPunctaObjsModel::setupModelData(ZObjsItem *parent) { QList<QVariant> data; m_punctaSourceToParent.clear(); m_punctaSourceToCount.clear(); m_punctaToRow.clear(); m_punctaSourceParentToRow.clear(); m_punctaSeparatedByFile.clear(); int sourceParentRow = 0; int numDigit = numDigits(m_doc->punctaList()->size()+1); for (int i=0; i<m_doc->punctaList()->size(); i++) { data.clear(); ZPunctum *p = m_doc->punctaList()->at(i); QFileInfo sourceInfo(p->source()); if (m_punctaSourceToParent.find(p->source()) != m_punctaSourceToParent.end()) { ZObjsItem *sourceParent = m_punctaSourceToParent[p->source()]; data << QString("puncta %1").arg(m_punctaSourceToCount[p->source()] + 1, numDigit, 10, QLatin1Char('0')) << p->score() << p->name() << p->comment() << p->x() << p->y() << p->z() << p->sDevOfIntensity() << p->volSize() << p->mass() << p->radius() << p->meanIntensity() << p->maxIntensity() << p->property1() << p->property2() << p->property3() << p->color() << sourceInfo.fileName(); m_punctaToRow[p] = m_punctaSourceToCount[p->source()]; m_punctaSourceToCount[p->source()]++; ZObjsItem *punctum = new ZObjsItem(data, p, sourceParent); punctum->setCheckState(p->isVisible() ? Qt::Checked : Qt::Unchecked); punctum->setToolTip(QString("puncta from: %1").arg(p->source())); sourceParent->appendChild(punctum); m_punctaSeparatedByFile[m_punctaSourceParentToRow[sourceParent]].push_back(m_doc->punctaList()->at(i)); } else { data << sourceInfo.fileName() << "score" << "name" << "comment" << "x" << "y" << "z" << "sDev" << "volSize" << "mass" << "radius" << "meanIntensity" << "maxIntensity" << "property1" << "property2" << "property3" << "color" << "source"; m_punctaSeparatedByFile.push_back(std::vector<ZPunctum*>()); ZObjsItem *sourceParent = new ZObjsItem(data, NULL, parent); sourceParent->setToolTip(QString("puncta source: %1").arg(p->source())); m_punctaSourceToParent[p->source()] = sourceParent; m_punctaSourceToCount[p->source()] = 0; parent->appendChild(sourceParent); m_punctaSourceParentToRow[sourceParent] = sourceParentRow++; data.clear(); data << QString("puncta %1").arg(m_punctaSourceToCount[p->source()] + 1, numDigit, 10, QLatin1Char('0')) << p->score() << p->name() << p->comment() << p->x() << p->y() << p->z() << p->sDevOfIntensity() << p->volSize() << p->mass() << p->radius() << p->meanIntensity() << p->maxIntensity() << p->property1() << p->property2() << p->property3() << p->color() << sourceInfo.fileName(); m_punctaToRow[p] = m_punctaSourceToCount[p->source()]; m_punctaSourceToCount[p->source()]++; ZObjsItem *punctum = new ZObjsItem(data, p, sourceParent); punctum->setCheckState(p->isVisible() ? Qt::Checked : Qt::Unchecked); punctum->setToolTip(QString("puncta from: %1").arg(p->source())); sourceParent->appendChild(punctum); m_punctaSeparatedByFile[m_punctaSourceParentToRow[sourceParent]].push_back(m_doc->punctaList()->at(i)); } } }
long charToNum(char name[], int nameLength, int index) { int i = index + 1; long value = (int)name[index]; while(i < nameLength) { value = value * pow(10, numDigits(name[i])); i++; } return value; }
bool BigInt::operator==(int n) const { if (number == 0) return false; int nd = numDigits(); if (nd == 0 && n == 0) return true; int digitsInInt = sizeof(int) / LA_BYTES_IN_DIGIT; if (nd > digitsInInt) return false; else return (((int) *this) == n); }
long_int multiply(long_int num1, long_int num2) { int digits1 = numDigits(num1); int digits2 = numDigits(num2); if(digits1 == 1 || digits2 == 1) { return num1 * num2; } long_int a = rightShift(num1, (digits1/2)); long_int c = rightShift(num2, (digits2/2)); long_int b = getSuffix(num1, digits1/2); long_int d = getSuffix(num2, digits2/2); long_int ac = multiply(a, c); long_int bd = multiply(b, d); long_int aplusbtimescplusd = multiply(a + b, c + d); long_int cof1 = tenPower((digits1/2) + (digits2/2)); long_int cof2 = tenPower(digits1/2); long_int sum_term_1 = cof1 * ac; long_int sum_term_2 = cof2 * (aplusbtimescplusd - ac - bd); return (sum_term_1 + bd + sum_term_2); }
int QLCDNumber::qt_metacall(QMetaObject::Call _c, int _id, void **_a) { _id = QFrame::qt_metacall(_c, _id, _a); if (_id < 0) return _id; if (_c == QMetaObject::InvokeMetaMethod) { if (_id < 9) qt_static_metacall(this, _c, _id, _a); _id -= 9; } #ifndef QT_NO_PROPERTIES else if (_c == QMetaObject::ReadProperty) { void *_v = _a[0]; switch (_id) { case 0: *reinterpret_cast< bool*>(_v) = smallDecimalPoint(); break; case 1: *reinterpret_cast< int*>(_v) = numDigits(); break; case 2: *reinterpret_cast< int*>(_v) = digitCount(); break; case 3: *reinterpret_cast< Mode*>(_v) = mode(); break; case 4: *reinterpret_cast< SegmentStyle*>(_v) = segmentStyle(); break; case 5: *reinterpret_cast< double*>(_v) = value(); break; case 6: *reinterpret_cast< int*>(_v) = intValue(); break; } _id -= 7; } else if (_c == QMetaObject::WriteProperty) { void *_v = _a[0]; switch (_id) { case 0: setSmallDecimalPoint(*reinterpret_cast< bool*>(_v)); break; case 1: setNumDigits(*reinterpret_cast< int*>(_v)); break; case 2: setDigitCount(*reinterpret_cast< int*>(_v)); break; case 3: setMode(*reinterpret_cast< Mode*>(_v)); break; case 4: setSegmentStyle(*reinterpret_cast< SegmentStyle*>(_v)); break; case 5: display(*reinterpret_cast< double*>(_v)); break; case 6: display(*reinterpret_cast< int*>(_v)); break; } _id -= 7; } else if (_c == QMetaObject::ResetProperty) { _id -= 7; } else if (_c == QMetaObject::QueryPropertyDesignable) { _id -= 7; } else if (_c == QMetaObject::QueryPropertyScriptable) { _id -= 7; } else if (_c == QMetaObject::QueryPropertyStored) { _id -= 7; } else if (_c == QMetaObject::QueryPropertyEditable) { _id -= 7; } else if (_c == QMetaObject::QueryPropertyUser) { _id -= 7; } #endif // QT_NO_PROPERTIES return _id; }
QValidator::State QDoubleValidator::validate(QString & input, int &) const { Q_D(const QDoubleValidator); QLocalePrivate::NumberMode numMode = QLocalePrivate::DoubleStandardMode; switch (d->notation) { case StandardNotation: numMode = QLocalePrivate::DoubleStandardMode; break; case ScientificNotation: numMode = QLocalePrivate::DoubleScientificMode; break; }; QByteArray buff; if (!locale().d()->validateChars(input, numMode, &buff, dec)) { QLocale cl(QLocale::C); if (!cl.d()->validateChars(input, numMode, &buff, dec)) return Invalid; } if (buff.isEmpty()) return Intermediate; if (b >= 0 && buff.startsWith('-')) return Invalid; if (t < 0 && buff.startsWith('+')) return Invalid; bool ok, overflow; double i = QLocalePrivate::bytearrayToDouble(buff.constData(), &ok, &overflow); if (overflow) return Invalid; if (!ok) return Intermediate; if (i >= b && i <= t) return Acceptable; if (d->notation == StandardNotation) { double max = qMax(qAbs(b), qAbs(t)); if (max < LLONG_MAX) { qlonglong n = pow10(numDigits(qlonglong(max))) - 1; if (qAbs(i) > n) return Invalid; } } return Intermediate; }
/* * function draw_clock() * * function for drawing the clock-face */ void InputBox::draw(void) { u8g->setPrintPos(x, y); u8g->setFont(u8g_font_6x10); u8g->print(label); int offset = numDigits(value); u8g->setPrintPos(x+(100 -(offset*6)),y); u8g->print(value); }
bool BigInt::operator>(int n) const { assert(number != 0); int nd = numDigits(); if (nd == 0 && n == 0) return false; // Both zero int digitsInInt = sizeof(int) / LA_BYTES_IN_DIGIT; if (nd > digitsInInt) return (number->sign > 0); // Consider separately case when high bit is set if ((number->digits[digitsInInt] & LA_HIGH_BIT) != 0) return (number->sign > 0); return (((int) *this) > n); }
int FindWord(char *word, Index *ind, char **result) { IndexLocationList *loc = Index_RetrieveEntry(ind,word); // The word was not found in the index if (loc == NULL) { char *notFound = "<br>Word %s not found\n"; // Minus 2 for the "%s" CHECK char *buffer = malloc( strlen(notFound) + strlen(word) -2 +1 ); sprintf(buffer,notFound,word); // Rewire the result pointer *result = buffer; return 0; } char *found = "<br>Word %s @ %s:%d\n"; int nCharsWritten = 0; // Create a buffer to hold the entire message char *buf = NULL; int buffSize = 0; while (loc) { // Subtract 6 because the string won't contain "%s %s %d" int strLen = strlen(found) + strlen(word) + strlen(loc->item.pathname) + numDigits(loc->item.offset) - 6; // Reallocate the buffer when it's too small to hold the message if(strLen + nCharsWritten > buffSize){ int newSize = 2*buffSize + strLen; buf = realloc(buf,newSize); buffSize = newSize; } // Copy the message into a buffer char temp[strLen]; sprintf(temp,found,word,loc->item.pathname,loc->item.offset); memcpy(buf + nCharsWritten,temp,strLen); nCharsWritten += strLen; loc = loc->nextLocation;; } // Append the null terminator buf[nCharsWritten] = 0; // Rewire the result pointer *result = buf; return 1; }
char *toStringPoly(unsigned long l){ //x^n+x^(n-1)...+X+C char* tempBinString; tempBinString=(char*)malloc((sizeof(l)*2+1)*4); tempBinString=toStringBin(l); //call to toStringBin() char* polyString; polyString=(char*)malloc((sizeof(l)*2+1)*40); // it takes 4 bits to represent one hex so the sting needs be 4 times as long int i = 0; for (; i < strlen(tempBinString); i++){ // added semicolon to front of for loop if (tempBinString[i]=='1') { if (strlen(polyString)!=0) // append plus every time except for greatest degree x { strcat(polyString,"+"); } if (i==strlen(tempBinString)-2)// regular x { strcat(polyString,"x"); } else if (i==strlen(tempBinString)-1)// rightmost char in string, this is our C term { strcat(polyString,"1"); } else { char *strToAppend; // look over possibly use strcat strToAppend=(char*)malloc(2+numDigits(i%strlen(tempBinString)+1));// 2+ for "x^" +1 for term char //call to numDigits() //malloc() http://www.cplusplus.com/reference/cstdlib/malloc/ // then figure out how many digits to store snprintf (strToAppend,sizeof(strToAppend),"x^%lu",(unsigned long)strlen(tempBinString)-i%strlen(tempBinString)); strcat(polyString,strToAppend); free(strToAppend); } } } free(tempBinString); printf("Output generated in toStringPoly() "); printf("\n%lu\n", polyString); return polyString; }
double guessGame(int max) { int answer, response = 0, guesses = 0; answer = rando(max); double start = time(0); while (response != answer) { printf("Enter your guess!\n"); scanf("%d", &response); guesses++; if (response > answer) { printf("Your guess is too high, try again.\n"); } else if (response < answer) { printf("Your guess is too low, try again.\n"); }; }; double end = time(0); double timespentCorr = (end - start)/(2 * numDigits(max)); double timespent = end - start; printf("Great, you guessed the correct number %d in %d guesses in %lf seconds.\n", answer, guesses, timespent); return timespentCorr; };
QValidator::State QDoubleValidatorPrivate::validateWithLocale(QString &input, QLocaleData::NumberMode numMode, const QLocale &locale) const { Q_Q(const QDoubleValidator); QByteArray buff; if (!locale.d->m_data->validateChars(input, numMode, &buff, q->dec, locale.numberOptions() & QLocale::RejectGroupSeparator)) { return QValidator::Invalid; } if (buff.isEmpty()) return QValidator::Intermediate; if (q->b >= 0 && buff.startsWith('-')) return QValidator::Invalid; if (q->t < 0 && buff.startsWith('+')) return QValidator::Invalid; bool ok, overflow; double i = QLocaleData::bytearrayToDouble(buff.constData(), &ok, &overflow); if (overflow) return QValidator::Invalid; if (!ok) return QValidator::Intermediate; if (i >= q->b && i <= q->t) return QValidator::Acceptable; if (notation == QDoubleValidator::StandardNotation) { double max = qMax(qAbs(q->b), qAbs(q->t)); if (max < LLONG_MAX) { qlonglong n = pow10(numDigits(qlonglong(max))) - 1; if (qAbs(i) > n) return QValidator::Invalid; } } return QValidator::Intermediate; }
bool allSameDigits( vector<int> nums ) { int c[10] = { 0 }; int mult = 1; int digitCount = 0; for( auto && num : nums ) { digitCount += numDigits( num ); while( num ) { c[num % 10] += mult; num /= 10; } mult *= -1; } int result = 1; for( int i = 0; i < 10; ++i ) { result &= c[i] == 0; } return result == 1 && digitCount % 6 == 0; }
int main(void) { int cases = getInt(); for(int c=1;c<=cases;c++) { long long int n = getInt(); long long int result = 0; while (n > 20) { int tg = numDigits(n) / 2; long long int secondHalf = n % power(tg); if (secondHalf > 1) { result += secondHalf - 1; n -= secondHalf - 1; } if (lastDigit(n) != 0 && reverse(n) < n) { result++; n = reverse(n); } secondHalf = n % power(tg); result += secondHalf + 1; n -= secondHalf + 1; } result += n; printf("Case #%d: %lld\n", c, result); } }
QValidator::State QLongDoubleValidator::validate(QString & input, int &) const { QByteArray buff; if (!validateChars(input, &buff, dec)) return QValidator::Invalid; if (buff.isEmpty()) return QValidator::Intermediate; if (q->b >= 0 && buff.startsWith('-')) return QValidator::Invalid; if (q->t < 0 && buff.startsWith('+')) return QValidator::Invalid; bool ok, overflow; long double i = bytearrayToLongDouble(buff.constData(), &ok, &overflow); if (overflow) return QValidator::Invalid; if (!ok) return QValidator::Intermediate; if (i >= q->b && i <= q->t) return QValidator::Acceptable; if (mNotation == StandardNotation) { long double max = qMax(qAbs(q->b), qAbs(q->t)); if (max < LLONG_MAX) { qlonglong n = pow10(numDigits(qlonglong(max))) - 1; if (qAbs(i) > n) return QValidator::Invalid; } } return QValidator::Intermediate; }
/*!\reimp */ QSize QLCDNumber::sizeHint() const { return QSize( 10 + 9 * (numDigits() + (smallDecimalPoint() ? 0 : 1)), 23 ); }
void HRSstreamStart(HRSstream_t s, void *filterFunction, int numSlices, HRSslice_t slices) { assert(s != NULL); if (s->type == HRS_BINARYSTREAM) { s->bs->filter = (int (*)(char, void *, char *, char *))filterFunction; openFirstBinaryFile(s->bs); } else if (s->type == HRS_GENERALSTREAM) { s->gs->filter = (int (*)(char, void *, Sfio_t *, char *))filterFunction; openFirstGeneralFile(s->gs); } else if (s->type == HRS_GENERATIVESTREAM) { s->gens->filter = (int (*)(char, void *, char *))filterFunction; } else if (s->type == HRS_MAPSTREAM) { s->ms->filter = (int (*)(char, void *, char *, char *))filterFunction; } if (numSlices == 0) /* filter only stream */ s->filterOnly = 1; else { int from_pipe[2]; int to_pipe[2]; int keySize; int recSize; Sfio_t *tp; fchandle *fch; int i; s->filterOnly = 0; /* set up fixcut to munge the data */ fch = fcopen(); for (i=0; i < numSlices; i++) { int bStrSize = numDigits(slices[i].begin); int eStrSize = numDigits(slices[i].end); int strSize = bStrSize + 1 + eStrSize + strlen(slices[i].description) + 1; char *str = HRSmalloc(strSize, "HRSstreamStart"); sfsprintf(str, strSize, "%d,%d%s", slices[i].begin, slices[i].end, slices[i].description); if (fcslice(fch, 'k', str) != 0) HRSerrorExit1("Fixcut error: %s\n" , fcerror(fch)); /* do we need to/can we free str here? */ } if ((recSize = fcready(fch, s->logicalSize)) < 0) HRSerrorExit1("Fixcut error: %s\n" , fcerror(fch)); keySize = recSize - s->logicalSize; pipe(from_pipe); pipe(to_pipe); if (fork() == 0) { /* child */ extern int HRSpuntExit; int ac; char **av; HRSpuntExit = 1; /* don't do any work on exit in the child */ av = buildSortStr(s, keySize, 0, 1, &ac); close(to_pipe[1]); close(from_pipe[0]); close(0); dup(to_pipe[0]); close(to_pipe[0]); close(1); dup(from_pipe[1]); close(from_pipe[1]); amrRSORT(ac, av); _exit(1); } else { /* parent */ char *logicalData; uchar *mungedData; close(to_pipe[0]); close(from_pipe[1]); tp = sfnew(NULL, NULL, SF_UNBOUND, to_pipe[1], SF_WRITE | SF_SHARE); logicalData = HRSmalloc(s->logicalSize, "HRSstreamStart"); while (getNextElement(s, logicalData) != 0) { int v; if ((mungedData = fcbuild(fch, (uchar *) logicalData, NULL)) == NULL) HRSerrorExit1("Fixcut error: %s\n" , fcerror(fch)); v = sfwrite(tp, mungedData, recSize); if (v == 0) HRSerrorExit1("stream write to %s failed\n", s->streamName); } sfclose(tp); fcclose(fch); s->lfp = sfnew(NULL, NULL, SF_UNBOUND, from_pipe[0], SF_READ | SF_SHARE); HRSfree(logicalData); } } }
unsigned numDigits(const unsigned n) { // NOT MINE http://stackoverflow.com/questions/3068397/finding-the-length-of-an-integer-in-c if (n < 10) return 1; return 1 + numDigits(n / 10); }
void Double2StringFilter::writeExtraAttributes(QXmlStreamWriter* writer) const { writer->writeAttribute("format", QString(QChar(numericFormat()))); writer->writeAttribute("digits", QString::number(numDigits())); }
/* returns 0. */ float eval(float x, float y, int& errval) { stack<float> values; // Stack of values to be evaluated float operands[2]; // Array to contain the two operands (assuming n=2 arguments for any operator) string s_vars[2]={ftos(x), ftos(y)}; // Store x and y in one array for easy iteration for(int thisvar=0; thisvar<2; thisvar++) // Substitute for each variable { vector<string> vec_var=shuntingYard(s_vars[thisvar]); cout << "Substituting variable... " << vtos(vec_var) << endl; // Go through vector, inserting 'x' or 'y' into all instances of variable for(int i=0; i<expression.size(); i++) { if(expression[i]==rel_var[thisvar]) { expression.erase(expression.begin()+i); expression.insert(expression.begin()+i, vec_var.begin(), vec_var.end()); i+=vec_var.size(); } } } cout << "After substitution: " << vtos(expression) << endl; // Debugging stuff, displays result cout << "Parsing tokens..." << endl; for(int i=0; i<expression.size(); i++) { string token=expression[i]; // If it's a number, push it to the stack if(isdigit(token[0])) values.push(atof(token.c_str())); // If it's an operator, evaluate else if(searchFor(token, operators, NUM_OPS)) { float result; if(values.size()<2) { // Not enough values errval=INSUFF; return 0.0; } operands[1]=values.top(); values.pop(); operands[0]=values.top(); values.pop(); // Evaluate the operator switch(token[0]) { case '.': result=operands[0]+operands[1]/pow(10, numDigits(operands[1])); cout << operands[1] << endl; break; case '^': if(operands[0]<0) { errval=IMAGINARY; return 0.0; } result=pow(operands[0], operands[1]); break; case '*': result=operands[0]*operands[1]; break; case '/': if(operands[1]==0) { errval=DIVZERO; return 0.0; } result=operands[0]/operands[1]; break; case '+': result=operands[0]+operands[1]; break; case '-': result=operands[0]-operands[1]; break; default: errval=OPER; return 0.0; } values.push(result); } else { errval=OPER; return 0.0; } } if(values.size()==1) { // That one value is the result errval=NONE; return values.top(); } else { // Problem, too many values on stack errval=VAL; return 0.0; } }