我遇到以下代码行的问题:
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;
}
}
}
答案 0 :(得分:1)
@main ifstream dataIn;
您没有使用此对象
@function read_data:
int count;
for ( count = 0; count < size; count++ )
{
dataIn >> num[count];
}
for (count = 0; count < size; count++)
{
dataIn >> den[count];
}
假设你的文件看起来像:
1 2 23 32 44 // numerators
2 3 1 99 24 // den
正确的阅读方式是:
int count = 0;
while( count < size && dataIn >> num[count++] ) // numerators
;
count = 0;
while( count < size && dataIn >> den[count++] )
;
@function showValues: 尝试改变
double answer;
answer = num[count] / den[count];
cout << " Fraction" << count + 1 << " "
<< num[count] << " / " << den[count]
<< " = " << answer << endl;
到:
double answer = static_cast<double>(num[count]) / den[count];
cout << " Fraction" << count + 1 << " "
<< num[count] << " / " << den[count] << " = " << answer << endl;
答案 1 :(得分:1)
在C和C ++中,如果你这样做,
double answer = 10 / 3;
你的回答是3.原因是你有2个整数并且会发生整数除法。然后,结果输出被隐式转换为double。所以步骤是,
要解决此问题,请告诉编译器您希望将其视为浮点除法。
double answer = 10.0 / 3;
这适用于,
编译器将隐式地将3转换为更大的double类型3.0。
因此,在您的代码中,您必须通过将至少一个除法参数转换为double来将整数除法转换为浮点除法。
double foo = num[count] / den[count];
简单地变成
double foo = num[count] / static_cast<double>(den[count]);
或者,如果一个或两个数组都是double类型,那么你就不会遇到需要强制转换的问题。