从两列中选择一个数字并计算

时间:2017-07-09 08:21:06

标签: c++ arrays while-loop fstream calculated-columns

给定文件包含<two-digit number, amount>对。然后取一个两位数的数字(称为X),并计算赢/输金额。赢/输规则是输入数字与X匹配,然后是胜利,获胜总数是(金额* 70);否则,它是(-amount)的损失。

  

For example: [ticket.txt] 09 10 13 15 25 21

如果折腾数为09,则机票的赢/输金额为(10 * 70 - 15 - 21)

如果投票数为42,则票数的赢/输金额为(-10 - 15 - 21)。

这是我的初学者项目。我坚持计算胜利金额和损失金额。 This is my problem

#include <iostream>
#include <fstream>

using namespace std;
int line1[100]; // array that can hold 100 numbers for 1st column
int line2[100]; // array that can hold 100 numbers for 2nd column
int main()
{
    int winNum, winAmount, lostAmount;
    int num = 0; // num start at 0
    ifstream inFile; 
    inFile.open("Ticket.txt"); //open File
    if (inFile.fail())
    {
        cout << "Fail to open the file" << endl;      
        return 1;
    }
    cout << "Numbers from File: " << endl;
    while (!inFile.eof()) // read File to end of file
        {
            inFile >> line1[num]; // read first column, the first column is the number that user choosing
            inFile >> line2[num]; // read second column, the second column is the amount of money that user paying
            cout << "\n" << line1[num] << "\t" << line2[num];
            ++num; 
        }
    inFile.close();
    cout << endl;
    cout << "Enter the toss-up number: "; // enter the win number
    cin >> winNum;
    if (line1[num] == winNum) 
    {
        winAmount = line2[num] * 70; //  number user choose = win number, winAmount = winAmount * 70 - lostAmount
        cout << winAmount;
        }
        else
        {
            lostAmount =- line2[num]; //number user choose != win number, the amount will be -lost amounts
cout << lostAmount;
        }
        cout << endl << endl;
        system("pause");
        return 0;
    }

2 个答案:

答案 0 :(得分:0)

当您测试line1[num] == winNum(以及之后执行的所有操作)时,您使用的是使用num修改的++num;值,这意味着您正在使用line1line2的空值或无意义值。例如,如果使用“ticket.txt”中显示的3行值,则它们存储在数组的位置0,1和2中,而num在结尾处的值为4。

如果我理解了你想要实现的目标,你应该将if-else语句放在一个从0到num的for循环中,然后在line1和{{1}上的每个操作应该使用循环变量作为索引来完成。 此外,如果您只想显示总金额,请在循环后移动line2

答案 1 :(得分:0)

您可以在代码末尾看到结果

BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(address);
BluetoothSocket mmSocket = null;

    try {
        mmSocket = device.createRfcommSocketToServiceRecord(UUID);
        mmSocket.connect();
        Log.d(TAG, "mmSocket returned");
    }
    ...