[英]Output not correct for my C++ program
So, I have the following problem: 所以,我有以下问题:
Will be writing functions for: 将为以下功能编写函数:
Example: 例:
tabl.in : tabl.in :
4
5 8 2 12
1 0 3 16
1 2 1 11
5 7 2 19
tabl.out : tabl.out :
2 1 3
where 哪里
(12+3+2+5)%10 = 22%10 = 2 (12 + 3 + 2 + 5)%10 = 22%10 = 2
22 is palindrome = 1 22是回文数= 1
1+2+2+1+7+5 = 18, 18/6=3 1 + 2 + 2 + 1 + 7 + 5 = 18,18/6 = 3
My code so far is: 到目前为止,我的代码是:
#include <fstream>
using namespace std;
ifstream fin("tabl.in");
ofstream fout("tabl.out");
void readn(int Arr[][51], int n) {
for (int i = 1; i <= n; i++)
for (int j = 1; j <= n; j++)
fin >> Arr[i][j];
}
int sumsec(int Arr[][51], int n) {
int s = 0;
float r;
for (int i = 1; i <= n; i++)
s = s + Arr[i][n - i + 1];
r = s % 10;
return r;
}
void pald(int Arr[][51], int n) {
int s = 0, pal = 0;
for (int i = 1; i < n; i++)
s = s + Arr[i][n - i + 1];
while (s != 0) {
pal = pal * 10 + s % 10;
s = s / 10;
}
if (pal == s)
fout << "1 ";
else
fout << "0 ";
}
int ambmd(int Arr[][51], int n) {
int s = 0, k;
float ame;
for (int i = 2; i <= n; i++) {
for (int j = 1; j <= i - 1; j++) {
s = s + Arr[i][j];
k++;
}
}
ame = s / k;
return ame;
}
int main() {
int Arr[51][51], n;
float r, ame;
fin >> n;
readn(Arr, n);
r = sumsec(Arr, n);
fout << r << " ";
pald(Arr, n);
ame = ambmd(Arr, n);
fout << ame;
}
But I have an issue with the palindrome()
function: my output file will have 2 0 3
written to it for the given array from the example, instead of 2 1 3
. 但是我对
palindrome()
函数有一个问题:对于示例中的给定数组,我的输出文件将写入2 0 3
,而不是2 1 3
。 What am I doing wrong? 我究竟做错了什么?
Your pald
function would work, if you compute s
the same way as you do in sumsec
and if s
would still contain the sum, after you compute pal
. 如果在计算
pal
之后, sumsec
与sumsec
相同的方式计算s
,并且s
仍包含总和,则您的pald
函数将起作用。
In your case, while (s != 0) {...}
, followed by if (pal == s) {...}
could be re-written as if (pal == 0)
, which is clearly not the intended solution. 在您的情况下,
while (s != 0) {...}
之后是if (pal == s) {...}
可以重写为if (pal == 0)
,显然不是预期的解决方案。 Just save your sum before computing pal
, then compare with the saved sum. 只需在计算
pal
之前保存您的总和,然后与保存的总和进行比较即可。
Also, change your loop condition for computing s
to for (int i = 1; i <= n; i++)
. 同样,将用于计算
s
循环条件更改为for (int i = 1; i <= n; i++)
。
int s = 0, pal = 0, sum = 0;
for (int i = 1; i <= n; i++)
s = s + Arr[i][n - i + 1];
sum = s;
while (s != 0) {
pal = pal * 10 + s % 10;
s = s / 10;
}
if (pal == sum)
fout << "1 ";
else
fout << "0 ";
You should also consider the various comments for code improvements, like not re-computing the sum in the pald
function. 您还应该考虑各种注释以改进代码,例如不要在
pald
函数中重新计算总和。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.