Effacer les filtres
Effacer les filtres

Difference between %d and %f?

720 vues (au cours des 30 derniers jours)
xxtan1
xxtan1 le 3 Août 2020
Réponse apportée : Steven Lord le 7 Juil 2024 à 15:47
Hi, I dont quite understand the difference between %d and %f and its usage in certain cases.
Does %d correspond to int in C and %f correspond to float?
What is the case I have to use %d instead of %f?

Réponse acceptée

Adam Danz
Adam Danz le 3 Août 2020
Modifié(e) : Adam Danz le 4 Août 2020
Refer to the documentation.
%d represents signed integers (base 10).
sprintf('John is %d years old', 7)
% 'John is 7 years old'
%f represents floating point numbers.
sprintf('The first 8 dp of pi are %.8f', pi)
% 'The first 8 dp of pi are 3.14159265'
%f can also be used to represent integers by rounding floating point inputs. %d cannot be used in this way.
sprintf('Pi is rounded to %.0f', pi)
% 'Pi is rounded to 3'
sprintf('Pi is rounded to %.d', pi)
% 'Pi is rounded to 3e+00'
  1 commentaire
JUNAID
JUNAID le 7 Juil 2024 à 10:21
I didn't understand.

Connectez-vous pour commenter.

Plus de réponses (1)

Steven Lord
Steven Lord le 7 Juil 2024 à 15:47
If you want to print integer values, you probably want to use %d.
If you want to print non-integer values, you probably want to use %f.
While you can use %f to print integer values (as per the second line of code below) if you try to use %d to print non-integer values it will actually switch to a different specifier (%e I believe, as per the note in the Notable Behavior of Conversions with Formatting Operators section of the description of the formatSpec input argument on the fprintf documentation page.)
fprintf("This uses the %%d format specifier: %d\n", 42)
This uses the %d format specifier: 42
fprintf("This uses the %%f format specifier: %f\n", 42)
This uses the %f format specifier: 42.000000
fprintf("This uses the %%d format specifier: %d\n", pi)
This uses the %d format specifier: 3.141593e+00
fprintf("This uses the %%f format specifier: %f\n", pi)
This uses the %f format specifier: 3.141593

Catégories

En savoir plus sur Multidimensional Arrays dans Help Center et File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by