演算子に余りがないかどうかを確認if
したい:/
int x = 0;
if (x = 16 / 4), if there is no remainder:
then x = x - 1;
if (x = 16 / 5), if remainder is not zero:
then x = x + 1;
に残りがあるかどうかを確認する方法はC
? そして
それを実装する方法は?
演算子に余りがないかどうかを確認if
したい:/
int x = 0;
if (x = 16 / 4), if there is no remainder:
then x = x - 1;
if (x = 16 / 5), if remainder is not zero:
then x = x + 1;
に残りがあるかどうかを確認する方法はC
? そして
それを実装する方法は?
%
Frist、剰余演算子が必要です:
if (x = 16 % 4){
printf("remainder in X");
}
注: float/double では機能しません。その場合は を使用する必要がありますfmod (double numer, double denom);
。
次に、必要に応じて実装します。
if (x = 16 / 4)
、残りがない場合、x = x - 1
; If (x = 16 / 5)
、その後x = x + 1
;コンマ,
演算子を使用すると、次のように単一のステップで実行できます(コメントを読んでください):
int main(){
int x = 0, // Quotient.
n = 16, // Numerator
d = 4; // Denominator
// Remainder is not saved
if(x = n / d, n % d) // == x = n / d; if(n % d)
printf("Remainder not zero, x + 1 = %d", (x + 1));
else
printf("Remainder is zero, x - 1 = %d", (x - 1));
return 1;
}
作業コード @codepade: first、second、thirdを確認してください。
if-condition で Comma Operator: を使用していることに注意してください。これは、 operator read: comma operator with an example,
を理解するためです。,
この目的には剰余演算子を使用します。
if(x%y == 0)
その後、残りはありません。
除算演算では、結果が浮動小数点の場合、整数部分のみが返され、小数部分は破棄されます。
剰余を扱うモジュラス演算子を使用できます。