【发布时间】:2014-04-01 02:06:44
【问题描述】:
以下代码行有问题:
double answer;
answer = num[count] / den[count]
cout << " Fraction" << count + 1 << " " << num[count]
<< " / " << den[count] << " = " << answer << endl;
为什么我的答案演绎不起作用?我忽略了什么吗?我正在使用数组并从单独的文本文件中获取数据。当我使用上面的代码时,我得到了要正确划分的数字,但答案不正确。结果是一个随机数,通常为 0 或 1。
这是我的代码:
#include <iostream>
#include <fstream>
#include <iomanip>
#include <cstdlib>
using namespace std;
void read_data(int num[], int den[], int size);
void showValues(int num[],int den[], int size);
int main()
{
const int size1 = 12;
const int size2 = 12;
ifstream dataIn;
int num[12];
int den[12];
read_data(num,den,size1);
cout << "Here are the fractions: " << endl;
showValues(num,den,size1);
system("PAUSE");
return 0;
}
void read_data(int num[], int den[], int size)
{
ifstream dataIn;
dataIn.open("walrus.txt");
if( dataIn.fail() )
{
cout << "File does not exist." << endl;
exit(1);
}
int count;
for ( count = 0; count < size; count++ )
{
dataIn >> num[count];
}
for (count = 0; count < size; count++)
{
dataIn >> den[count];
}
dataIn.close();
}
void showValues(int num[],int den[], int size)
{
int count;
for (count = 0; count < size; count++)
{
if (den[count] == 0)
{
cout << " Fraction" << count + 1 << " "
<< num[count] << " /" << den[count]
<< " Is invalid" << endl;
}
else
{
double answer;
answer = num[count] / den[count];
cout << " Fraction" << count + 1 << " "
<< num[count] << " / " << den[count]
<< " = " << answer << endl;
}
}
}
【问题讨论】:
-
MCVE 会有所帮助,尤其是数组的声明。
-
请显示所有相关代码 - 数组等的数据类型及其值。
-
请记住,如果
num[count]和den[count]是整数类型,则除法会丢弃任何余数/小数部分,例如它会将任何>= 0和< 1舍入到0、5/2 = 2等。您可能想使用double(num[count]) / den[count]。 -
有什么理由在打印之前阅读所有内容?如果您立即处理数据,您需要更少的空间(并获得灵活性)。
-
像现在一样读入,但只够一行输出,计算,打印行,重复。当文件为空时,您就完成了。