如何在命令提示符下从用户一次获得3个数字,以便可以对现有数组执行点积运算?例如:
我先定义
int myArray[3] = {1,2,3};
现在,用户以“ i,j,k”格式输入自然数。 该程序退出
myArray[0]*userArray[0] + myArray[1]*userArray[1] + myArray[2]*userArray[2]
即
1*a + 2*b + 3*c
我能够轻松地使用预定义的数组完成此操作。但是,当我尝试将用户输入标识为数组的件时,出了一些问题。该程序认为数字不同,位置不同或结构不同,导致答案是否定的。
[部分]我的程序在下面。目标与示例相同:
#include "stdafx.h"
#include <cstdlib>
#include <iostream>
#include <string>
#include <vector>
#include <sstream>
#include <limits>
#include <tuple>
int main()
{
int nNumCup = 0, nNumLem = 0, nNumSug = 0, nNumIce = 0;
float fCoH = 20.00, fCostCup25 = 1.99, fCostCup50 = 2.49, fCostCup100 = 2.99;
int arrnStoreInput01A[3];
std::cout << "Go to Cups \n \n";
std::cout << "Cups are availible in packs of 25, 50 and 100. \n"
"Please enter three numbers in \"i,j,k\" format for the \n"
"respective amounts of each of the following three products \n"
"you want to buy: \n \n"
"A) 25-pack of cups for " << fCostCup25 << "\n"
"B) 50-pack of cups for " << fCostCup50 << "\n"
"C) 100-pack of cups for " << fCostCup100 << "\n \n"
"For example, type \"0,4,0\" to purchase 4 packages of 50 cups or \n"
"type \"3,2,1\" to buy 3 packages of 25 cups, 2 packages of 50 cups \n"
"and 1 package of 100 cups. \n \n";
//This is where the user inputs "i,j,k". I entered "3,2,1" in the command prompt.
std::cin >> arrnStoreInput01A[0] >> arrnStoreInput01A[1] >> arrnStoreInput01A[2];
float arrnCostCup[3] = { fCostCup25,fCostCup50,fCostCup100 };
float fStoreInput01AdotfCoH = arrnStoreInput01A[0] * arrnCostCup[0]
+ arrnStoreInput01A[1] * arrnCostCup[1]
+ arrnStoreInput01A[2] * arrnCostCup[2];
int arrnQuantCup[3] = { 25,50,100 };
if (fStoreInput01AdotfCoH <= fCoH){
fCoH = fCoH - fStoreInput01AdotfCoH;
nNumCup = nNumCup + arrnStoreInput01A[0] * arrnQuantCup[0]
+ arrnStoreInput01A[1] * arrnQuantCup[1]
+ arrnStoreInput01A[2] * arrnQuantCup[2];
}
else
std::cout << "Not enough cash on hand.";
std::cout << "you have " << nNumCup << " cups! \n";
std::cout << "you have " << fCoH << " left in cash!";
//Inspecting what the program thinks the user-inputed array is
//(next lines) reveals that it is interpreting "3,2,1"
//erroneously as 3 -858993460 -858993460
for (auto const value : arrnStoreInput01A)
{
std::cout << value << ' ';
}
return 0;
}
我还要附上命令提示符输出的图片,因为这是非常说明性的,并且可以说很容易解释(请参阅文章顶部)。
答案 0 :(得分:2)
使用for循环将用户输入存储在数组中。用户完成操作后,便可以执行操作。像这样:
#include <iostream>
#include <vector>
int main()
{
std::vector<int> userInput ;
std::vector<int> predefinedArray{1,2,3};
for(int i=0;i<3;i++)
{
int tmp;
std::cout<< "Introduce input numer " <<i<<": " ;
std::cin >> tmp;
userInput.push_back(tmp);
}
std::cout<<userInput[0]*predefinedArray[0]+
userInput[1]*predefinedArray[1]+
userInput[2]*predefinedArray[2]<<std::endl;
return 0;
}
我建议您像上面的代码一样使用std::vector
。
答案 1 :(得分:2)
看看operator>>
的工作方式。它读取直至逗号的整数(或任何非整数的整数)。您必须从输入流中删除逗号才能获得下一个数字。
您可以使用ignore:
std::cin >> arrnStoreInput01A[0];
std::cin.ignore(1,',');
std::cin >> arrnStoreInput01A[1];
std::cin.ignore(1,',');
std::cin >> arrnStoreInput01A[2];