gpt4 book ai didi

c++ - 除法答案未正确执行

转载 作者:行者123 更新时间:2023-11-28 02:52:20 25 4
gpt4 key购买 nike

我在使用以下代码行时遇到了问题:

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;
}
}
}

最佳答案

@main ifstream dataIn;你没有使用这个对象

@函数读取数据:

 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 显示值:尝试改变

   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;

关于c++ - 除法答案未正确执行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22775515/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com