[英]How to have multiple int values in every element in a one dimensional array?
i want to fill one one dimensional array with two int values.我想用两个 int 值填充一个一维数组。
When i run my code without brackets around the values i get only the frist int and when i run it with brackets around the values i get only the second int.当我在值周围不带括号运行代码时,我只得到第一个 int,当我在值周围用括号运行它时,我只得到第二个 int。
Output should be like x/y Output 应该像 x/y
thank you for your time.感谢您的时间。
int main()
{
cBruch cBruch[7];
cBruch[0] = (3, 4);
cBruch[1] = (24, -6);
cBruch[2] = -5, -3;
cBruch[3] = -14, 22;
cBruch[4] = 21, 45;
cBruch[5] = 7, -9;
cBruch[6] = 2, 3;
for (int i = 0; i < 7; i++)
{
cBruch[i].ausgabe();
}
return 0;
}
.h 。H
class cBruch
{
private:
int zaehler;
int nenner;
int ggt(int a, int b);
void kuerzen();
public:
cBruch(int zaehler_in = 0, int nenner_in = 1);
~cBruch();
void ausgabe(); //output
};
.cpp .cpp
cBruch::cBruch(int zaehler_in, int nenner_in)
{
zaehler = zaehler_in;
nenner = nenner_in;
cout << "Konstruktor Zaehler = " << zaehler << " Nenner = " << nenner << endl;
}
cBruch::~cBruch()
{
cout << "Destruktor Zaehler = " << zaehler << " Nenner = " << nenner << endl;
}
void cBruch::ausgabe()
{
cout << "Bruch: " << zaehler << "/" << nenner << "\tGleitkommazahl: "<< double(zaehler) / nenner << endl;
}
You should initialize your array like following:你应该像下面这样初始化你的数组:
cBruch cBruch[] = {{3, 4},{24, -6},{-5, -3},{-14, 22},{21, 45},{7, -9},{2, 3}};
The comma operator will always evaluate both sides and return the right hand side. 逗号运算符将始终评估双方并返回右侧。 It also has the lowest precedence of all opearators.它的 优先级也是所有运算符中最低的。
So, this:所以这:
cBruch[2] = -5, -3;
evaluates to:评估为:
(cBruch[2] = -5), -3;
And this:和这个:
cBruch[0] = (3, 4);
Will evaluate to:将评估为:
cBruch[0] = 4;
You probably should use an array (or better yet a std::array
) of for example std::pair<int, int>
.您可能应该使用例如std::pair<int, int>
的数组(或者更好的是std::array
)。
Apparently I can't read... You need {} rather than ().显然我看不懂...您需要 {} 而不是 ()。 – HolyBlackCat – 圣黑猫
Thanks.谢谢。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.