[英]Problem using Printf and Scanf in a HackerRank practice problem
我已經嘗試在 Hackerrank 中解決這個問題已經有一段時間了。我面臨的問題是,我是一個初學者,在閱讀問題時最終使用cin
和cout
而不是scanf
和printf
,同時接受用戶輸入能夠檢查我的推理是否正確,盡管我已經使用前者正確解決了問題,但在使用后者時遇到了困難。
這是我一直試圖解決的問題:
https://www.hackerrank.com/challenges/acm-icpc-team/problem
這是使用cin
和cout
的代碼:
#include<iostream>
#include<stdio.h>
using namespace std;
int main(){
int n,m;
cin>>n>>m;
int a[n][m]={};
for (int i = 0; i < n; i++)
{
for (int j = 0; j < m; j++)
{
cin>>a[i][j];
}
}
int b[n*(n-1)/2][m]={};
int x=0;
for (int i = 0; i < n-1; i++)
{
for (int j = i+1; j < n; j++)
{
for (int k = 0; k < m; k++)
{
b[x][k] = (a[i][k]|a[j][k]);
}
x=x+1;
}
}
int count = 0;
int c[n*(n-1)/2]={};
for (int i = 0; i < n*(n-1)/2; i++)
{
c[i]=0;
}
for (int i = 0; i < n*(n-1)/2; i++)
{
for (int j = 0; j < m; j++)
{
if (b[i][j]==1)
{
count++;
}
}
c[i]=count;
count=0;
}
for (int i = 0; i < n; i++)
{
int temp=c[i];
int j=i;
while (j>0 && temp<c[j-1])
{
c[j]=c[j-1];
j=j-1;
}
c[j]=temp;
}
int sum=0;
for (int i = 0; i < n*(n-1)/2; i++)
{
if (c[ n*(n-1)/2 - 1]==c[i])
{
sum++;
}
}
cout<<c[ n*(n-1)/2 - 1]<<endl;
cout<<sum;
return 0;
}
在使用“printf”和“scanf”編寫整個代碼時,我只是替換了“cin and cout”:
#include <iostream>
#include <stdio.h>
using namespace std;
int main()
{
int n, m;
scanf("%d", "%d", &n, &m);
int a[n][m] = {};
for (int i = 0; i < n; i++)
{
for (int j = 0; j < m; j++)
{
scanf("%d", &a[i][j]);
}
}
int b[n * (n - 1) / 2][m] = {};
int x = 0;
for (int i = 0; i < n - 1; i++)
{
for (int j = i + 1; j < n; j++)
{
for (int k = 0; k < m; k++)
{
b[x][k] = (a[i][k] | a[j][k]);
}
x = x + 1;
}
}
int count = 0;
int c[n * (n - 1) / 2] = {};
for (int i = 0; i < n * (n - 1) / 2; i++)
{
c[i] = 0;
}
for (int i = 0; i < n * (n - 1) / 2; i++)
{
for (int j = 0; j < m; j++)
{
if (b[i][j] == 1)
{
count++;
}
}
c[i] = count;
count = 0;
}
for (int i = 0; i < n; i++)
{
int temp = c[i];
int j = i;
while (j > 0 && temp < c[j - 1])
{
c[j] = c[j - 1];
j = j - 1;
}
c[j] = temp;
}
int sum = 0;
for (int i = 0; i < n * (n - 1) / 2; i++)
{
if (c[n * (n - 1) / 2 - 1] == c[i])
{
sum++;
}
}
printf("sum");
return 0;
}
我還附上了一份 output 的副本,我正在使用以前的代碼:當我手動提供空白字符時,output 運行良好,但是當我使用printf
運行相同的代碼時,因為某些原因而無法使用scanf
:
有人可以指導我哪里出錯了嗎?
你有4個問題。
scanf("%d", "%d", &n, &m);
不會將整數加載到 n 和 m 中。 它將加載嘗試將 1 integer 加載到第二個參數(在這種情況下為“%d”)然后忽略 n 和 m。 要在同一個 scanf 中加載多個整數,您需要在同一個字符串中添加所有 %d: scanf("%d%d", &n, &m);
scanf("%1d", &a[i][j]);
printf("%d", sum);
c[ n*(n-1)/2 - 1]
的值,第二個沒有。 您可以在第二個 printf 中打印出來: printf("%d\n", c[ n*(n-1)/2 - 1]); //note use of \n to force a new line on output
或在同一個 printf 中:
printf("%d\n%d", c[ n*(n-1)/2 - 1], sum);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.