Outputting an equation with variables and text

3 次查看(过去 30 天)
I have the following variables:
a=0.9; %CH4 reactant
b=0.2; %H2O reactant
c=0.1; %CO2 reactant
d=1.8; %O2 reactant
e=2; %H20 product
f=1; %O2 product
These are coefficients to a chemical equation. I am using if else if statements to manipulate the coefficients for the reaction balance. I need to output the chemical reaction balance for the user, for example:
The balance for the chemical reaction is: 0.9CH4 + 0.2H2O + 0.1CO2 + 1.8O2 -> 2H2O + 1O2
How may I type code in matlab to incorporate both text and values of variables?

回答(2 个)

Peng Li
Peng Li 2020-4-14
a=0.9; %CH4 reactant
b=0.2; %H2O reactant
c=0.1; %CO2 reactant
d=1.8; %O2 reactant
e=2; %H20 product
f=1; %O2 product
fprintf("the balance for the chemical reaction is: %.1fCH4 + %.1fH2O " ...
+ "+ %.1fCO2 + %.1fO2 -> %dH2O + %dO2\r", ...
a, b, c, d, e, f);
the balance for the chemical reaction is: 0.9CH4 + 0.2H2O + 0.1CO2 + 1.8O2 -> 2H2O + 1O2
Is this what you want?

Star Strider
Star Strider 2020-4-14
编辑:Star Strider 2020-4-14
Try this:
ChemEqn = sprintf('%gCH4 + %gH20 + %gCO2 + %gO2 -> %gH2O + %gO2',a,b,c,d,e,f)
producing:
ChemEqn =
'0.9CH4 + 0.2H20 + 0.1CO2 + 1.8O2 -> 2H2O + 1O2'
See the documentation for sprintf (or fprintf) to understand how it works.
.

类别

Help CenterFile Exchange 中查找有关 Chemistry 的更多信息

产品


版本

R2019b

Community Treasure Hunt

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

Start Hunting!

Translated by