我正在研究一个完整的搜索问题,并仔细阅读了代码,但无法弄清楚为什么我的程序不断出现空输出文件错误。谁能帮我找到为什么会这样吗?问题语句在下面,然后是我的代码。
问题陈述:回文数是向前和向后读取相同的数字。数字12321是典型的回文。
给出一个以数字为底的B(2 <= B <= 20以10为底),打印所有整数N(1 <= N <= 300底10),以使N的平方在以B为底数时是回文的;还可以打印回文方块的值。使用字母“ A”,“ B”等来表示数字10、11等。
在底数B中打印数字及其平方。
我的代码:
#include <iostream>
#include <cmath>
#include <algorithm>
#include <fstream>
#include <string>
using namespace std;
//utility function to raise number to a power
int power(int first, int second)
{
int total = 1;
for (int i = 0; i < second; i++)
{
total *= first;
}
return total;
}
//convert the number to the proper base
int convert(string num, int base1)
{
int sum = 0;
for (int i = num.size() - 1; i >= 0; i--)
sum += num[i] * power(base1, num.size() - i);
return sum;
}
//test if converted number is a palindrome
bool is_pal(int number)
{
//if the #ofdigits is even
if (number % 2 == 0)
{
int mid = (to_string(number).size()) / 2;
string str_num = to_string(number);
string half1;
for (int i = 0; i < mid; i++)
half1 += str_num[i];
string half2;
for (int i = str_num.size()-1; i > mid-1; i--)
half2 += str_num[i];
if (half1 == half2)
return true;
return false;
}
//if the #ofdigits is odd
else
{
int mid1 = (to_string(number).size() - 1) / 2;
int mid2 = (to_string(number).size() + 1) / 2;
string str_num = to_string(number);
string half1;
for (int i = 0; i < mid1; i++)
{
half1 += str_num[i];
}
string half2;
for (int i = str_num.size()-1; i > mid2-1; i--)
{
half2 += str_num[i];
}
if (half1 == half2)
return true;
return false;
}
}
int main()
{
ofstream fout("palsquare.out");
ifstream fin("palsquare.in");
int base;
fin >> base;
for (int i = 1; i < 300; i++)
{
if (is_pal(convert(to_string((power(i, 2))), base)))
{
fout << convert(to_string(i), base) << " " << convert(to_string(power(i, 2)), base) << "\n";
}
}
return 0;
}
答案 0 :(得分:1)
除了我的评论外,将数字转换为基数B的常用格式为:
std::string convert_base(int B, int num)
{
assert(B>1&&num>=0);
char const digits[] ="0123456789AB...Z";
std::vector<char> str;
do
{
int const d = num%B;
num /= B;
str.push_back(digits[d]);
} while(num);
return std::string(str.rbegin(), str.rend());
}
那么完整的答案是:
bool is_pal(std::string const & str)
{
return std::equal(str.cbegin(), str.cend(), std.crbegin());
}
int const pow2_i = i*i;
std::string const pow2_baseB = convert_base(B, pow2_i);
if(is_pal(pow2_baseB)) ...