c++ - 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;
}
}
}
我愿意接受任何建议和意见,谢谢。:)
解决方案
您将受益于更多功能。将事物分解为代表单一目的的最小代码块可以使调试代码变得更加容易。你需要问问自己,什么是空缺数字。它是一个可以被第一个和最后一个数字整除的数字。那么,我们需要什么来解决这个问题呢?
我们需要知道一个数字有多少位数字。我们需要知道数字的第一个数字和最后一个数字。
因此,首先要创建一个函数来解决这些问题。然后,您将更容易找出最终的解决方案。
#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
}
推荐阅读
- java - 如何使用 srcML 实现数据流分析?
- python - Selenium 找不到 div 输入字段元素
- javascript - 如何将 API 数据传递给子组件
- windows-10 - Sharepoint 驱动器已映射但无法访问?
- mariadb - 查询 MariaDB 的安装文件夹?
- python - 从元组列表中查找所有出现的最大值?
- object - 调试时从 Visual Studio 2019 导出对象
- curl - 从 ProcessMaker 发出 curl 请求时出现 RuntimeException
- android - 在 Flutter 中使用 GetConnect 库获取错误代码 415 不受支持的媒体类型
- javascript - 运行 npm 测试时出现 nyc 正则表达式拒绝服务漏洞