Effacer les filtres
Effacer les filtres

coefficients checked asking for him

1 vue (au cours des 30 derniers jours)
Nagy Sándor
Nagy Sándor le 12 Oct 2021
Commenté : Walter Roberson le 19 Juil 2024
I would like to check the coefficients of a quadratic equation as a real number. I would like to establish a vector for an equation ax^2+bx+c--> [a b c] . in case of the variable if you are a character writes zero let the felhaszáló ask for the number again with an error message.How I may make this?

Réponses (1)

BhaTTa
BhaTTa le 19 Juil 2024
To create a MATLAB script that checks the coefficients of a quadratic equation and ensures they are real numbers and coeffecients are not equal to 0, you can use the following approach. The script will prompt the user to input the coefficients and will check if they are valid real numbers. If a user inputs a character or an invalid number, the script will display an error message and prompt the user to enter the number again.
Here’s a step-by-step script to achieve this:
% Function to prompt the user for a real number input
function coeff = getRealNumber(prompt)
while true
coeff = input(prompt, 's'); % Read input as a string
num = str2double(coeff); % Convert string to number
if isnan(num) || num==0 % Check if the conversion was not successful
disp('Error: Please enter a valid real number.');
else
coeff = num; % Assign the valid number to coeff
break; % Exit the loop if input is valid
end
end
end
% Main script to get the coefficients of the quadratic equation
disp('Enter the coefficients for the quadratic equation ax^2 + bx + c:');
a = getRealNumber('Enter coefficient a: ');
b = getRealNumber('Enter coefficient b: ');
c = getRealNumber('Enter coefficient c: ');
% Create the coefficients vector
coefficients = [a, b, c];
% Display the coefficients vector
disp('The coefficients vector is:');
disp(coefficients);
  1 commentaire
Walter Roberson
Walter Roberson le 19 Juil 2024
Close, but 0 should be a valid coefficient. For example the user might want to enter 1*x^2 + 0*x - 1 (in other words, x^2 - 1)
A result of 0 from str2double() does not indicate an error.
(It is true, though, that you might generally want to restrict the first coefficient to be non-zero.)

Connectez-vous pour commenter.

Catégories

En savoir plus sur MATLAB Coder 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