首页 > 解决方案 > C++ Gapful Numbers 崩溃

问题描述

我正在做这个程序,在这个程序中,我可以打印间隙数字,一直到一个特定的值。操作是正确的,但是,由于某种原因,在打印了几个值后程序崩溃了,我能做些什么来解决这个问题?

这是我的代码:

#include<math.h>
#include<stdlib.h>
using namespace std;

void gapful(int);
bool gapCheck(int);

int main(){
    int n;

    cout<<"Enter a top number: ";
    cin>>n;

    gapful(n);

    system("pause");
    return 0;
}

void gapful(int og){
    for(int i=0; i<=og; i++){
        fflush(stdin);
        if(gapCheck(i)){
            cout<<i<<" ";
        }
    }
}

bool gapCheck(int n){
    int digits=0;
    int n_save,n1,n2,n3;

    if(n<100){
        return false;
    }
    else{
        n_save=n;
        while(n>10){
            n/=10;
            digits++;
        }
        digits++;
        n=n_save;
        n1=n/pow(10, digits);
        n2=n%10;
        n3=n1*10 + n2;
        if(n%n3 == 0){
            return true;
        }
        else{
            return false;
        }
    }
}

我愿意接受任何建议和意见,谢谢。:)

标签: c++crashnumbers

解决方案


您将受益于更多功能。将事物分解为代表单一目的的最小代码块可以使调试代码变得更加容易。你需要问问自己,什么是空缺数字。它是一个可以被第一个和最后一个数字整除的数字。那么,我们需要什么来解决这个问题呢?

我们需要知道一个数字有多少位数字。我们需要知道数字的第一个数字和最后一个数字。

因此,首先要创建一个函数来解决这些问题。然后,您将更容易找出最终的解决方案。

#include<math.h>
#include <iostream>
using namespace std;

void gapful(int);
bool gapCheck(int);
int getDigits(int);
int digitAt(int,int);

int main(){
    int n;
    cout<<"Enter a top number: " << endl;
    cin>>n;
    gapful(n);
    return 0;
}

void gapful(int og){
    for(int i=1; i<=og; ++i){
        if(gapCheck(i)){
            cout<<i << '-' <<endl;
        }
    }
}

int getDigits(int number) {
    int digitCount = 0;
    while (number >= 10) {
        ++digitCount;
        number /= 10;
    }
    return ++digitCount;
}

int digitAt(int number,int digit) {
    int numOfDigits = getDigits(number);
    int curDigit = 0;
    if (digit >=1 && digit <= numOfDigits) { //Verify digit is in range
        while (numOfDigits != digit) { //Count back to the digit requested
            number /=10;
            numOfDigits -=1;
        }
        curDigit = number%10; //Get the current digit to be returned.
    } else {
        throw "Digit requested is out of range!";
    }
    return curDigit;
}


bool gapCheck(int n){
    int digitsN = getDigits(n);
    if (digitsN < 3) { //Return false if less than 3 digits. Single digits do not apply and doubles result in themselves.
        return false;
    }
    int first = digitAt(n,1) * 10; //Get the first number in the 10s place
    int second = digitAt(n,digitsN); //Get the second number
    int total = first + second; //Add them
    return n % total == 0; //Return whether it evenly divides
}

推荐阅读