问题是关于打印两位数 n 的数字,我遇到了运行时错误
The question is about printing digits of two digit number n, I'm encountering a runtime error
给定一个两位数 n,打印该数字的两个数字。
输入格式:
第一行表示测试用例个数T.
接下来的 T 行每行包含一个数字 ni。
输出格式:
T 行,每行包含由 space.
分隔的数字 ni 的两位数字
约束条件
1 <= T <= 100000
10 <= 镍 <= 99
错误:运行时错误 (SIGSEGV)
我无法确定问题出在代码中,因为它对两个数字工作正常,而对 4 个或更多数字给出运行时错误。
除了使用 for 循环两次之外,还有其他方法可以解决这个问题吗?
#include <bits/stdc++.h>
using namespace std;
int main()
{
int t;
int arr[t];
cin>>t;
for(int i=0;i<t;i++)
{
cin>>arr[i];
}
int c;
int b;
for(int i=0;i<t;i++)
{
c=(arr[i]/10);
if(c!=0)
{
b=arr[i]%(c*10);
}
else
{
b=arr[i];
}
cout<<c<<" "<<b<<endl;
}
return 0;
}
拳头,你声明了t
,但是没有初始化,所以是未初始化的。尝试使用该值会导致未定义的行为。
其次,VLA 不是有效的 C++,请参阅 here。您必须改用 std::vector
。
第三,你不需要使用int
。
所以,你应该这样做:
#include <iostream>
#include <vector>
#include <string>
int main()
{
int t{};
std::cin >> t;
std::vector<std::string> arr(t);
for(int i = 0; i < t; i++)
{
std::cin >> arr[i];
}
for(const auto &i : arr)
{
std::cout << i[0] << ' ' << i[1] << '\n';
}
}
给定一个两位数 n,打印该数字的两个数字。
输入格式: 第一行表示测试用例个数T.
接下来的 T 行每行包含一个数字 ni。
输出格式: T 行,每行包含由 space.
分隔的数字 ni 的两位数字约束条件
1 <= T <= 100000 10 <= 镍 <= 99
错误:运行时错误 (SIGSEGV)
我无法确定问题出在代码中,因为它对两个数字工作正常,而对 4 个或更多数字给出运行时错误。 除了使用 for 循环两次之外,还有其他方法可以解决这个问题吗?
#include <bits/stdc++.h>
using namespace std;
int main()
{
int t;
int arr[t];
cin>>t;
for(int i=0;i<t;i++)
{
cin>>arr[i];
}
int c;
int b;
for(int i=0;i<t;i++)
{
c=(arr[i]/10);
if(c!=0)
{
b=arr[i]%(c*10);
}
else
{
b=arr[i];
}
cout<<c<<" "<<b<<endl;
}
return 0;
}
拳头,你声明了t
,但是没有初始化,所以是未初始化的。尝试使用该值会导致未定义的行为。
其次,VLA 不是有效的 C++,请参阅 here。您必须改用 std::vector
。
第三,你不需要使用int
。
所以,你应该这样做:
#include <iostream>
#include <vector>
#include <string>
int main()
{
int t{};
std::cin >> t;
std::vector<std::string> arr(t);
for(int i = 0; i < t; i++)
{
std::cin >> arr[i];
}
for(const auto &i : arr)
{
std::cout << i[0] << ' ' << i[1] << '\n';
}
}