除法答案执行不正确

用户名

我无法处理以下代码行:

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;
             }
        }
 }
用户名

@mainifstream 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;

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章