我有四个列表,每个列表包含84种不同的速率,我希望能够根据输入的信息使用if / else语句来访问这些速率,我希望有比将每个类型输入一个数组更有效的方法。
最简单的方法是什么?任何提示都将非常有帮助,我只需要一个起点。
#include "MaleNonSmoker.txt"
using namespace std;
double ratesmn[85] = {
#include "MaleNonSmoker.txt"
- 1
};
#include <iostream>
#include <string>
#define STARTAGE 15
int main() {
double const *rates;
rates = ratesmn;
int age;
cout << "How old are you?\n";
cin >> age;
double myrate = ratesmn[age - STARTAGE];
return 0;
}
我得到的错误来自第1行:语法错误:'constant'和第7行:'太多初始化程序'
如果数字不变,则在运行时实际上不需要从文件中读取数字。您也可以在编译时使用它们。
使用您喜欢的任何工具使用数组创建四个文件,但在每个数字后添加一个逗号,因此如下所示:
51,
52,
53,
在您的c ++代码中,定义4个数组,并使用它#include
来包含文本文件中的数字。
int ratesms[85] = {
#include "ratesms.txt"
-1 // add another number because the txt file ends with a comma
};
对其他阵列执行相同的操作。
在代码中,确定要使用的列表,并设置指向该列表的指针,例如
int const *rates;
if ( /* smoking male */ )
rates = ratesms;
else if ( /* other variations */ )
rates = ...
然后像这样使用它;
#define STARTAGE 15
int age=35; // example
int myrate=rates[age-STARTAGE];
如果您不想从数组索引中减去起始年龄,则还可以在数组中添加15个虚拟数字;
int ratesms[100] = {
0,0,0,0,0,
0,0,0,0,0,
0,0,0,0,0,
#include "ratesms.txt"
-1 // add another number because the txt file ends with a comma
};
现在ratesms[15]
将包含txt文件中的第一个数字。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句