為什么它給出錯誤的計數在這個問題中,我們必須找出有多少元素大于陣列的下一個元素
#include using namespace std;
int main() {
//number of testcases
int t;
cin>>t;
while(t--){
//taking number of elements in an array
int n,count;
cin>>n;
//taking array
int a[n];
count=0;
for(int i=1;i<=n;i ){
cin>>a[n];
}
//checking array
for(int j=1;j<=n-1;j ){
if(a[j]>a[j 1])
{
count ;
}
}
cout<<count<<endl;
}
return 0;
}
輸入 5 1 2 3 4 1 預期輸出 1 通過上述代碼輸出 2
uj5u.com熱心網友回復:
您的代碼有幾個問題:
問題 1
當您撰寫時,您將超出陣列的范圍,a從而導致未定義的行為
cin >> a[n]; //undefined behavior
請注意,陣列的索引從 C 開始,0而不是從1C 開始。
問題 2
在標準 C 中,陣列的大小必須是編譯時常量。這意味著您的代碼中的以下內容不正確:
int n;
cin>>n;
int a[n]; //NOT STANDARD C BECAUSE n IS NOT A CONSTANT EXPRESSION
更好的是使用std::vector而不是內置陣列。
int n = 0;
std::cin >> n;
std::vector<int> a(n); //this creates a vector of size n
//take input from user
for(int& element: a)
{
std::cin >> element;
}
int count = 0;
for(int i = 0; i< n - 1; i)
{
if(a[i] > a[i 1])
{
count;
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/466854.html
上一篇:在2個ArrayLists中獲取匹配和不匹配物件的最有效方法
下一篇:按最少兩個值排序
