【发布时间】:2015-09-08 20:45:13
【问题描述】:
我的 C 项目是一个 Windows 控制台应用程序,它从用户的音乐项目中获取拍号和 BPM,并以秒为单位返回小节的长度。
我正在尝试使用 do-while 循环来添加“继续/退出?”在每次成功计算结束时提示
这是该函数的源代码。它根据用户输入执行一次计算,然后终止。
#include <stdio.h>
#include <stdlib.h>
int main()
{
char timeSignature[6];
float BPM;
float beatsPerBar;
float barLength;
printf("Enter the working time signature of your project:");
scanf("%s",timeSignature);
beatsPerBar = timeSignature[0]-'0';
printf("Enter the beats per minute:");
scanf("%f", &BPM);
barLength = BPM / beatsPerBar;
printf("%f\n", barLength);
return 0;
}
每次计算成功后,我想提示用户选择“y”返回初始输入提示或“n”结束程序并退出命令提示。 稍后的更新包括一个 do-while 循环,旨在添加该功能。
#include <stdio.h>
#include <stdlib.h>
#include <windows.h>
#include <unistd.h>
int main()
{
do{
char timeSignature[6];
char anotherCalculation;
float BPM;
float beatsPerBar;
float barLength;
printf("Enter the working time signature of your project:");
scanf("%s",timeSignature);
beatsPerBar = timeSignature[0]-'0';
/*
* Subtracts the integer value of the '0' character (48) from the integer value
* of the character represented by the char variable timeSignature[0] to return
* an integer value equal to the number character itself.
*/
printf("Enter the beats per minute:");
scanf("%f", &BPM);
barLength = BPM / beatsPerBar;
printf("%f\n", barLength);
Sleep(3);
printf("Would you like to do another calculation? (Y/N)");
scanf(" %c", &anotherCalculation);
}while((anotherCalculation = 'Y'||'y'));
if((anotherCalculation != 'Y'||'y'))
{
printf("Goodbye!");
return 0;
}
return 0;
}
当我编译时,没有错误,但当我运行它时,程序在任何输入后循环。为什么代码忽略了我的真实分配?我该怎么做才能解决这个问题?
【问题讨论】:
-
emmmm。循环在哪里?
-
您发布的代码中没有 do-while 循环。
-
抱歉,我花了一点时间来查看/修复它。
-
这一行:
if((anotherCalculation != 'Y'||'y'))完全没有必要,也不会产生预期的结果。这是不必要的,因为“while()”语句已经检查过了。它不会按预期工作,因为在 C 中一次只能检查一个条件,建议:if((anotherCalculation != 'Y' && anotherCalculation != 'y'))然而,正如我所说,完全不需要这个“if”语句 -
以秒为单位的柱形时间计算
barLength = BPM / beatsPerBar不正确(反转)。应该是barLength = beatsPerBar * 60.0 / BPM
标签: c loops do-while truthiness