简体   繁体   English

C ++只有第一个答案行正确

[英]c++ only first answer line correct

I get problem with my program ,it prints correct only first line answer here is my .txt file,first number (3) is shops number,second number (5) is products number ,other lines is prices for products 我的程序出现问题,它只打印正确的第一行答案,这里是我的.txt文件,第一个数字(3)是商店编号,第二个数字(5)是产品编号,其他行是产品价格

3 5
1.27 2.92 3.45 1.09 0.89
1.08 2.25 3.75 1.12 0.69
0.98 2.48 3.62 1.10 0.72

And here`s my results.txt file ,in witch are all results of each line 这是我的results.txt文件,在女巫中是每行的所有结果

 9.62
 8.89
 8.90

My program code: 我的程序代码:

#include <iostream>
#include <fstream>

using namespace std;

int main()
{
    double dienos, results;
    int shops;

    ifstream fin ("duomenys1.txt");
    fin >> shops;

    for( int shop = 1; shop <= 3; shop++ ) {
        results = 0;
        fin >> dienos;

        for ( int pricelist = 1; pricelist <= 5; pricelist++ ) {
            double price;
            fin >> price;
            results += price;

        }
        cout << results << endl;

    }
}

I suspect that in: 我怀疑在:

ifstream fin ("duomenys1.txt");
    fin >> shops;

    for( int shop = 1; shop <= 3; shop++ ) {
        results = 0;
        fin >> dienos;

The fin >> dienos should be outside of your loop. fin >> dienos应该在循环之外。

Also both loops are hard-coded, rather than using the values read. 同样,两个循环都是硬编码的,而不是使用读取的值。

Can you try this code: 您可以尝试以下代码:

#include <iostream>
#include <fstream>

using namespace std;

int main()
{
    double dienos, results;
    int shops;

    ifstream fin("duomenys1.txt");
    fin >> shops;
    fin >> dienos;

    for (int shop = 1; shop <= shops; shop++)
    {
        results = 0;
        for (int pricelist = 1; pricelist <= dienos; pricelist++)
        {
            double price;
            fin >> price;
            results += price;
        }
        cout << results << endl;
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM