我想知道如何将一个数组与两个数组进行比较,但有一些规则:
在我的代码中,我需要输入 8 位数字来组成循环 - 好的,我做到了。现在我需要将 array = m[3]
与两个不同的数组进行比较:
第一个数组必须是 (if m[i]%2==0) ...
第二个数组必须是 (if m[i]%2!=0) ...
因此,如果我从键盘输入主数组 (m[3])
中的那三行:
12345678
12345689
12344331
输入后,我需要在这两个不同的数组中设置使用 %
,或以某种方式仅对最后一位数字进行检查(其工作方式相同)。
因此,在输入 3 行后进行下一步:
arrA=12345678
arrB=12345689 12344331
#include <iostream>
#include <conio.h>
#include <string>
#include <cstdlib>
#include <stdlib.h>
using namespace std;
int main()
{
int i,n;
char m[3];
for(i=1; i<=3; i++)
{
cout<<i<<". Fak nomer: "<<endl;
do
{
cin>>m[i];
gets(m);
}
while (strlen(m)!=7);
cout<<"As integer: "<<atoi(m);
}
}
最佳答案
据我了解,您正在尝试将三个正整数读入名为 m
的数组,但您希望确保以下内容:
- 三个数都是八位数
- 第一个数 (
m[0]
) 是偶数 - 第二个数字 (
m[1]
) 是奇数
如果 m
可以是一个整数数组,那么就不需要从字符串到 int 的转换了。要从控制台读取三个整数,请使用:
// m is now an array of integers
int m[3];
// loops from m[0] to m[2]
for(int i = 0; i < 3; i++)
{
cout<<i<<": "<<endl;
do
{
cin>>m[i];
}
while (!(m[i] >= 1e7 && m[i] < 1e8));
// m[i] must be greater than or equal to 10000000 and less than 100000000
// before continuing
}
通过使 m
成为整数数组,检查偶数或奇数变得更容易:
if (m[0] % 2 == 0)
cout << "m[0] is even" << endl;
if (m[1] % 2 != 0)
cout << "m[1] is odd" << endl;
关于c++ - 字符(字符串)到整数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13337493/