[英]Why does this LAPACK program work correctly when I provide the matrix directly, but not when I read it from a file?
[英]why this code does not work only when i provide a number having zero in it ? for example t=1 and string = "1012"
在這個問題中,我必須做的是:找到沒有。 給定字符串中的數字是字符串表示的完整數字的除數。
對於沒有 0 的數字,它工作正常。 例如 t=1 , s="12" , output=2
#include<bits/stdc++.h>
using namespace std;
int main()
{
string s;
long long t,i,n,ct;
cin>>t;
while(t--)
{
ct=0;
cin>>s;
n=stoi(s);
for(i = 0; i < s.length(); i++)
{
if(n%(s[i]-'0') == 0 && s[i] != '0')
{
ct++;
}
}
cout<<ct<<endl;
}
}
if(n%(s[i]-'0') == 0 && s[i] != '0')
首先,這是錯誤的順序。 在嘗試除法類型操作之前,您要確保它不是'0'
。 這樣做的原因是 C++ 使用短路操作,因此在以下代碼中,如果xyzzy
為 false,則永遠不會評估plugh
:
if (xyzzy && plugh)
如果xyzzy
是一個“危險的”操作,當plugh
為 false 時不應該發生,那么你會遇到麻煩。
在您的特定代碼中,您將首先嘗試在檢查數字之前評估除法。 因此,它將允許執行除以零,這不是一個好主意。 使用會更安全:
if ((s[i] != '0') && (n % (s[i] - '0') == 0))
您的代碼中還有一些其他小問題,例如有符號/無符號比較,或者不是真正需要使用long long
(a) ,或者沒有遵循在需要變量的地方而不是在某些時候聲明變量的准則然后之前(例如在函數的頂部)。
但if
語句中子表達式的順序很可能是您的直接問題。
(a)你預計這些字符串會持續多久? :-)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.